3

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.

Giampaolo Rodolà
  • 12,488
  • 6
  • 68
  • 60

2 Answers2

4

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
0

Use the __file__ attribute:

>>> import string
>>> string.__file__
'/usr/lib/python2.6/string.pyc'
AJ.
  • 27,586
  • 18
  • 84
  • 94