VigneshChennai
VigneshChennai

Reputation: 576

How to get the full namespace of a module after its imported in python

from foo.bar import bar

print(get_namespace(bar))

I want the above code snippet to print the "foo.bar.bar"

How to do it in python3 ?

Upvotes: 0

Views: 155

Answers (1)

unutbu
unutbu

Reputation: 879601

Every imported module is listed in sys.modules. So you could iterate through sys.modules to find the path associated with the module:

import sys
def get_module_name(mod):
    for path, module in sys.modules.items():
        if mod == module:
            return path
    raise ValueError('module not found')


from foo.bar import bar
print(get_module_name(bar))
# foo.bar.bar

Since the word namespace is reserved for a different concept, I've renamed the function get_module_name.

Upvotes: 2

Related Questions