Inspect the import path string from the object

If the object is a class or module function, I need to get the absolute import path as a string. Example:

>>> from a.b.c import foo
>>> get_import_path(foo)
'a.b.c.foo'

I tried to look into the verification module, but there is nothing to do.

+3
source share
2 answers

What you are trying to do is inherently impossible. fooit just doesn’t know how you imported it; it can even be imported in several ways. An example in my Linux box:

>>> from os.path import normpath
>>> from posixpath import normpath as normpath2
>>> normpath is normpath2
True

So, normpathand normpath2is one and the same functional object. It is not possible to display information about how they were imported.

However, sometimes this can help find the attribute of __module__your function:

>>> normpath.__module__
posixpath
>>> normpath2.__module__
posixpath

__module__ , , , .

+4

__file__:

>>> import string
>>> string.__file__
'/usr/lib/python2.6/string.pyc'
0

All Articles