Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full package module name

Tags:

python

inspect

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.

like image 290
Hubro Avatar asked Jul 28 '12 22:07

Hubro


People also ask

How do I find the package modules in Python?

Inside the package, you can find your modules by directly using __loader__ of course. That only works for modules, not packages. Try it on Python's logging package to see what I mean. Logging contains two modules: handlers and config.

How do I print a Python module name?

A module can find out its own module name by looking at the predefined global variable __name__.

What is __ package __?

That is, if a module is in a package, __package__ is set to the package name to enable explicit relative imports. Specifically: When the module is a package, its __package__ value should be set to its __name__ .


1 Answers

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

like image 192
unddoch Avatar answered Sep 30 '22 16:09

unddoch