MRocklin
MRocklin

Reputation: 57281

Get package of Python object

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?

Upvotes: 6

Views: 4751

Answers (1)

wim
wim

Reputation: 362826

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.

Upvotes: 4

Related Questions