获取 Python 个对象的包

Get package of Python object

给定一个对象或类型,我可以使用 inspect

获取对象的模块

例子

在这里,给定一个函数,我得到包含该函数的模块:

>>> inspect.getmodule(np.memmap)
<module 'numpy.core.memmap' from ...>

然而我真正想要的是获取与包对应的顶级模块,在本例中是numpy而不是numpy.core.memmap

>>> function_that_I_want(np.memmap)
<module 'numpy' from ...>

给定一个对象或模块,如何获取顶层模块?

如果您导入了子模块,那么顶层模块也必须已经加载到 sys.modules 中(因为导入系统就是这样工作的)。所以,像这样愚蠢而简单的东西应该是可靠的:

import sys, inspect

def function_that_I_want(obj):
    mod = inspect.getmodule(obj)
    base, _sep, _stem = mod.__name__.partition('.')
    return sys.modules[base]

该模块的 __package__ attribute may be interesting for you also (or future readers). For submodules, this is a string set to the parent package's name (which is not necessarily the top-level module name). See PEP366 了解更多详情。