Get full package module name

Question:

For verbose debug messages in my application I’m using a function that returns a helpful prefix. Consider the following example:

import inspect

def get_verbose_prefix():
    """Returns an informative prefix for verbose debug output messages"""
    s = inspect.stack()
    module_name = inspect.getmodulename(s[1][1])
    func_name = s[1][3]

    return '%s->%s' % (module_name, func_name)

def awesome_function_name():
    print "%s: Doing some awesome stuff right here" % get_verbose_prefix()

if __name__ == '__main__':
    awesome_function_name()

This outputs:

test->awesome_function_name: Doing some awesome stuff right here

My issue is: When I have a module in a package, for instance ‘myproject.utilities.input’, the module name returned from get_verbose_prefix is still just ‘input’, not ‘myproject.utilities.input’. This drastically reduces the helpfulness of the prefix in large projects when there can be several ‘input’ modules in different submodules all working together.

So my question is: Is there a simple way of retrieving the full module name within it’s package in Python? I’m planning on expanding the get_verbose_prefix function to check for ‘__init__.py’ files in the parent directories of the module to extrapolate it’s full name, but first I’d like to know if there’s an easier way to do it.

Asked By: Hubro

||

Answers:

Try using the __name__ attribute of the module.

Answered By: BrenBarn

__name__ always contains the full name of the module. (Other than __main__ on main, of course.)

Answered By: unddoch

A simple way of retrieving the full module name within its package:

print(__file__)
Answered By: Tung Nguyen

the other answers don’t account for __name__ becoming __main__ for the program entry point or don’t handle it properly.

this works for me:

def python_module() -> str:
    stack = inspect.stack()
    module = inspect.getmodule(stack[1][0])
    if module is None:
        raise ValueError("module not found")
    res = module.__name__
    if res != "__main__":
        return res
    package = module.__package__
    if package is None:
        package = ""
    mfname = module.__file__
    if mfname is None:
        return package
    fname = os.path.basename(mfname)
    ext = ".py"
    if fname.endswith(ext):
        fname = fname[:-len(ext)]
    if fname == ("__init__", "__main__"):
        return package
    return f"{package}.{fname}"
Answered By: Josua Krause
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.