39

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.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Hubro
  • 56,214
  • 69
  • 228
  • 381
  • 2
    Note: in the context of Python packaging, "package name" ≠ "import path". Packages can contain modules and namespaces that aren't necessarily named after the package itself. – Błażej Michalik Aug 20 '20 at 22:13

4 Answers4

49

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

Asclepius
  • 57,944
  • 17
  • 167
  • 143
unddoch
  • 5,790
  • 1
  • 24
  • 37
  • 1
    I suppose that's true, but how do I get to the actual module from the context of my prefix function? – Hubro Jul 28 '12 at 22:25
  • 20
    Never mind, I figured that out: `inspect.getmodule(s[1][0]).__name__`. Also you should edit in that `__name__` doesn't actually always return the full name of the module since it returns `__main__` on the executed module – Hubro Jul 28 '12 at 22:33
  • 1
    What is `s` in `inspect.getmodule(s[1][0]).__name__`? – Quentin Roy Jun 22 '17 at 05:27
  • 1
    @QuentinRoy `s = inspect.stack()` – 0x416e746f6e Aug 11 '17 at 11:13
  • 5
    That feeling when a [buried comment by the questioner](https://stackoverflow.com/questions/11705055/python-get-full-package-module-name#comment15525398_11705103) answers the question better than any of the actual answers. – Cecil Curry Jan 03 '19 at 04:54
8

Try using the __name__ attribute of the module.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
4

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

print(__file__)
Asclepius
  • 57,944
  • 17
  • 167
  • 143
Tung Nguyen
  • 1,486
  • 2
  • 18
  • 13
3

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}"