Reputation: 576
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
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