1

How can one get the fully qualified name of a module in Python, at the module level?

For example, let's say this is the file structure:

foo
├── setup.py
└── bar
    └── baz
        └── spam.py

From within the spam.py file at the module level, how can I get the fully qualified module name "bar.baz.spam"?


There is __file__, which one can pair with inspect.getmodulename(__file__) to get the module name "spam". However, how can I turn this into "bar.baz.spam"?

Intrastellar Explorer
  • 3,005
  • 9
  • 52
  • 119

1 Answers1

1

Try something like this:

from bar.baz import spam

print(spam.__name__)

If the name being imported is not a module, you can get the module name and object name like this:

from bar.baz.spam import MyClass

print(MyClass.__module__, MyClass.__name__)
Shaheed Haque
  • 644
  • 5
  • 14