I'm curious if it's possible to access the name of the parent module that some other module is imported into.
For instance, if I have a module (moduleA
) and a parent is module, foo.py
, into which it will be imported into, is it possible for moduleA
to know where foo
is located ?
def print_parent_module():
os.path.asbpath(#somehow access filename of parent module)
import moduleA
print moduleA.print_parent_module()
>>> "foo.py"
I ran into a similar issue. You could make use of __name__
:
parent_name = '.'.join(__name__.split('.')[:-1])
Or if you try to access the module directly (not the OP's question but related), see my answer in Is there a way to access parent modules in Python
No. Imported modules do not hold any form of state which stores data related to how they are imported.
I think the better question is, why would you even want to do it this way? You're aware that if foo.py
is indeed your __main__
then you can easily get the name foo.py
out of it (by using sys.argv)? And if foo.py
is an imported module instead, then you obviously already know the name of foo.py
and its location, etc. at the time that you import it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With