Get package of Python object

ぃ、小莉子 提交于 2021-02-10 05:51:17

问题


Given an object or type I can get the object's module using the inspect package

Example

Here, given a function I get the module that contains that function:

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

However what I really want is to get the top-level module that corresponds to the package, in this case numpy rather than numpy.core.memmap.

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

Given an object or a module, how do I get the top-level module?


回答1:


If you have imported the submodule, then the top-level module must also be loaded in sys.modules already (because that's how the import system works). So, something dumb and simple like this should be reliable:

import sys, inspect

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

The module's __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 for more details.



来源:https://stackoverflow.com/questions/43462701/get-package-of-python-object

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