获取函数的原始定义模块
Getting a function's module of original definition
给定一个 class 或函数,有没有办法找到最初定义的模块的完整路径? (即使用 def xxx
或 class xxx
。)
我知道有 sys.modules[func.__module__]
。但是,如果 func
被导入到包的 __init__.py
中,那么 sys.modules
将简单地重定向到 __init__.py
,因为该函数已被引入该命名空间,就我而言理解去。
一个具体的例子:
>>> 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'>
很明显,broadcast
在__init__.py
中没有定义;它只是通过 these from module import *
语句之一带入命名空间。
如果能看到在源代码中的什么地方定义了 np.broadcast
就好了(不管文件扩展名是 .c 还是 .py)。这可能吗?
您的理解:
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.
错了。 __init__.py
导入一个东西不会影响那个东西的 __module__
。
您在 numpy.broadcast
中看到的行为发生是因为 C 类型实际上没有 "defining module" 与 Python 中编写的类型相同的方式。 numpy.broadcast.__module__ == 'numpy'
因为 numpy.broadcast
是 written in C 并且声明它的名字是 "numpy.broadcast"
,并且 C 类型的 __module__
是由它的名字决定的。
至于如何获得 class 或函数的 "module of original definition",你真正拥有的最好的是 __module__
和其他经过 __module__
.[=25 的函数=]
给定一个 class 或函数,有没有办法找到最初定义的模块的完整路径? (即使用 def xxx
或 class xxx
。)
我知道有 sys.modules[func.__module__]
。但是,如果 func
被导入到包的 __init__.py
中,那么 sys.modules
将简单地重定向到 __init__.py
,因为该函数已被引入该命名空间,就我而言理解去。
一个具体的例子:
>>> 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'>
很明显,broadcast
在__init__.py
中没有定义;它只是通过 these from module import *
语句之一带入命名空间。
如果能看到在源代码中的什么地方定义了 np.broadcast
就好了(不管文件扩展名是 .c 还是 .py)。这可能吗?
您的理解:
However, if
func
is imported in a package's__init__.py
, thensys.modules
will simply redirect to that__init__.py
, because the function has been brought into that namespace, as far as my understanding goes.
错了。 __init__.py
导入一个东西不会影响那个东西的 __module__
。
您在 numpy.broadcast
中看到的行为发生是因为 C 类型实际上没有 "defining module" 与 Python 中编写的类型相同的方式。 numpy.broadcast.__module__ == 'numpy'
因为 numpy.broadcast
是 written in C 并且声明它的名字是 "numpy.broadcast"
,并且 C 类型的 __module__
是由它的名字决定的。
至于如何获得 class 或函数的 "module of original definition",你真正拥有的最好的是 __module__
和其他经过 __module__
.[=25 的函数=]