Robert Christie
Robert Christie

Reputation: 20685

How do I retrieve a modules path when I have a class from that module

In python, If I have a class foo, I can call foo.__module__ to get a string with the name of the module it is part of.

If I have a module bar, I can call bar.__file__ to get a string with the path where the module was loaded from.

How, when I only have class foo can I get the path of the module it is part of? (foo.__module__ returns a string, not an instance of the module it names)

Upvotes: 2

Views: 193

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881487

For such introspection tasks, I always recommend using Python standard library's inspect module: it can handle some corner cases &c and makes the whole process much smoother. For your specific task, inspect.getsourcefile can be handy -- e.g., consider...:

>>> from sched import scheduler as someclass
>>> import inspect
>>> inspect.getsourcefile(someclass)
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/sched.py'

this always tries to give you the .py file rather than sometimes the .py file and sometimes a .pyc file instead -- not a big deal, but one more useful "regularity".

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

sys.modules is a mapping from module name to module:

sys.modules[foo.__module__].__file__

Upvotes: 6

Related Questions