Skip to content Skip to sidebar Skip to footer

In Python, Is There A Way To Find The Module That Contains A Variable Or Other Object From The Object Itself?

As an example, say I have a variable defined where there may be multiple from __ import * from ____ import * etc. Is there a way to figure out where one of the variables in the n

Solution 1:

This is why it is considered bad form to use from __ import * in python in most cases. Either use from __ import myFunc or else import __ as myLib. Then when you need something from myLib it doesn't over lap something else.

For help finding things in the current namespace, check out the pprint library, the dir builtin, the locals builtin, and the globals builtin.


Solution 2:

No, the names defined by from blah import * don't retain any information about where they came from. The values might have a clue, for example, classes have a __module__ attribute, but they may have been defined in one module, then imported from another, so you can't count on them being the values you expect.


Solution 3:

Sort-of, for example:

>>> from zope.interface.common.idatetime import *
>>> print IDate.__module__
'zope.interface.common.idatetime'
>>> print Attribute.__module__
'zope.interface.interface'

The module of the Attribute may seem surprising since that is not where you imported it from, but it is where the Attribute type was defined. Looking at zope/interface/common/idatetype.py, we see:

from zope.interface import Interface, Attribute

which explains the value of __module__. You'll also run into problems with instances of types imported from other modules. Suppose that you create an Attribute instance named att:

>>> att = Attribute('foo')
>>> print att.__module__
'zope.interface.interface'

Again, you're learning where the type came from, but not where the variable was defined.

Quite possibly the biggest reason to not use wildcard imports is that you don't know what you're getting and they pollute your namespace and possibly clobber other types/variables.

>>> class Attribute(object):
...    foo = 9
...
>>> print Attribute.foo
9
>>> from zope.interface.common.idatetime import *
>>> print Attribute.foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Attribute' has no attribute 'foo'

Even if today the import * works without collision, there is no guarantee that it won't happen with future updates to the package being imported.


Solution 4:

If you call the method itself in the interpreter it will tell you what it's parent modules are.

For example:

>>> from collections import *
>>> deque
<type 'collections.deque'>

Post a Comment for "In Python, Is There A Way To Find The Module That Contains A Variable Or Other Object From The Object Itself?"