开发者

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

开发者 https://www.devze.com 2022-12-22 07:01 出处:网络
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.

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 th开发者_运维百科e module it is part of? (foo.__module__ returns a string, not an instance of the module it names)


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

sys.modules[foo.__module__].__file__


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

0

精彩评论

暂无评论...
验证码 换一张
取 消