Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the name of the 'parent' module from an imported module?

Tags:

python

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 ?

ModuleA

def print_parent_module(): 
    os.path.asbpath(#somehow access filename of parent module) 

foo.py

import moduleA 

print moduleA.print_parent_module()
>>> "foo.py"
like image 858
Zack Yoshyaro Avatar asked Sep 22 '13 20:09

Zack Yoshyaro


2 Answers

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

like image 102
Dorian B. Avatar answered Oct 23 '22 04:10

Dorian B.


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.

like image 41
Shashank Avatar answered Oct 23 '22 06:10

Shashank