Skip to content Skip to sidebar Skip to footer

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.ge

Solution 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.


Post a Comment for "Get Package Of Python Object"