How to get the current running module path/name

This works for me:

__loader__.fullname

Also if I do python -m b.c from a\ I get ‘b.c’ as expected.

Not entirely sure what the __loader__ attribute is so let me know if this is no good.

edit: It comes from PEP 302: http://www.python.org/dev/peps/pep-0302/

Interesting snippets from the link:

The load_module() method has a few responsibilities that it must
fulfill before it runs any code:

  • It should add an __loader__ attribute to the module, set to the
    loader object. This is mostly for introspection, but can be used
    for importer-specific extras, for example getting data associated
    with an importer.

So it looks like it should work fine in all cases.

Leave a Comment