Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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)

like image 861
Robert Christie Avatar asked Jan 19 '26 08:01

Robert Christie


2 Answers

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

sys.modules[foo.__module__].__file__
like image 134
Ignacio Vazquez-Abrams Avatar answered Jan 21 '26 06:01

Ignacio Vazquez-Abrams


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".

like image 28
Alex Martelli Avatar answered Jan 21 '26 07:01

Alex Martelli