Getting a function's module of original definition

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

Given a class or function, is there a way to find the full path of the module where it is originally defined? (I.e. using def xxx or class xxx.)

I'm aware that there is sys.modules[func.__module__]. However, if func is imported in a package's __init__.py, then sys.modules will simply redirect to that __init__.py, because the function has been brought into that namespace, as far as my understanding goes.

A concrete example:

>>> import numpy as np >>> import sys  >>> np.broadcast.__module__ 'numpy'  >>> sys.modules[np.broadcast.__module__] <module 'numpy' from '/Users/brad/.../site-packages/numpy/__init__.py'> 

Obviously, broadcast is not defined in __init__.py; it is just brought into the namespace with one of these from module import * statements.

It would be nice to see where in the source np.broadcast is defined (regardless of the file extension, be it .c or .py). Is this possible?

回答1:

Your understanding:

However, if func is imported in a package's __init__.py, then sys.modules will simply redirect to that __init__.py, because the function has been brought into that namespace, as far as my understanding goes.

is wrong. __init__.py importing a thing has no effect on that thing's __module__.

The behavior you're seeing with numpy.broadcast happens because C types don't really have a "defining module" the same way types written in Python do. numpy.broadcast.__module__ == 'numpy' because numpy.broadcast is written in C and declares its name to be "numpy.broadcast", and a C type's __module__ is determined from its name.

As for how to get a class or function's "module of original definition", the best you really have is __module__ and other functions that go through __module__.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!