Search code examples
pythonimportinspect

Inspect import path string from object


If an object is a module's class or function I need to retrieve 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 inspect module but there's nothing to do that.


Solution

  • What your are trying to do is inherently impossible. foo simply does not know how you imported it -- it might even have been imported in multiple different ways. Example on my Linux box:

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

    So normpath and normpath2 are the same function object. It's impossible to deduce the information in which way they were imported.

    That said, it sometimes might help to look at the __module__ attribute of your function:

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

    The __module__ attribute is not always defined, and if it is defined, it does not always contain the information you are looking for.