2
votes

I need a function that returns the name of the package of the module from which the function was called. Getting the module's name is easy:

import inspect

module_name = inspect.currentframe().f_back.f_globals['__name__']

And stripping the last part to get the module's package is also easy:

package_name = '.'.join(module_name.split('.')[:-1])

But if the function is called from a package's __init__.py, the last part of the name should not be stripped. E.g. if called from foo/bar/__init__.py, module_name in the above example will be set to 'foo.bar', which is already the name of the package.

How can I check, from the module name or the module object, whether it refers to a package or a module?

The best way I found is getting the module object's __file__ attribute, if it exists, and check whether it points to a file whose name is __init__ plus extension. But this seems very brittle to me.

2

2 Answers

1
votes

from the module object:

module.__package__

is available for a couple that I looked at, and appears to be correct. it may not give you exactly what you want though:

import os.path
import httplib2
import xml.etree.ElementTree as etree

os.path.__package__
<blank... this is a builtin>
httplib2.__package__
'httplib2'
etree.__package__
'xml.etree'

you can use

function.__module__

also, but that gives you the module name, not the actual module - not sure if there is an easier way to get the module object itself than importing again to a local variable.

etree.parse.__module__
'xml.etree.ElementTree'

os.path.split.__module__
'ntpath'

The good thing is this appears to be more correct, following the actual location of things, e.g.:

httplib2.Response.__module__
'httplib2'
httplib2.copy.copy.__module__
'copy'
httplib2.urlparse.ParseResult.__module__
'urlparse'

etc.

1
votes

This is what importlib.__import__() does, which needs to re-implement most of the Python's built-in import logic and needs to find a module's package to support relative imports:

# __package__ is not guaranteed to be defined or could be set to None
# to represent that it's proper value is unknown
package = globals.get('__package__')
if package is None:
    package = globals['__name__']
    if '__path__' not in globals:
        package = package.rpartition('.')[0]
module = _gcd_import(name, package, level)

So it seems that there is no reliable "direct" way to get a module's package.