Reputation: 29
How do you determine the name of the importing module within the module that is being imported. I have the partial solution, but not the complete one.
The code is: A.py
import B
if __name__ == '__main__':
print 'This a test'
The B.py
import sys
import C
if sys.argv[0] == 'A':
doSomething()
At this point, I'm all set because within module B, I know that name of the main that invoked the importing which in this case is A. However, within B, an import of C is requested, and it is in C that I want to know whether B imported C? How is this done?
Upvotes: 3
Views: 148
Reputation: 187
you can try interpreter-stack or traceback. Both will give you the stack's function calls, so this is not exactly the solution you want (modules).
Upvotes: 0
Reputation: 6234
sys.argv[0]
is not a name of module when import
was performed. This is name of executable file.
On the other side, inside Python module __name__
equals to a) module name if it's executed by importing, b) "__main__"
if it was executed as script.
Module doesn't "know" who performed import
(no "parent" attribute or something like this). Define your behavior with different functions and call them from different modules.
Upvotes: 2
Reputation: 25855
I doubt this is actually what you want to do, however. Note, in particular, that the top-level code in B will only run once, no matter how many times the module is imported from however many places.
For example, if you also import module D somewhere which imports module C before module B gets to, then your code in C for when it is imported from B will never run.
I think it is probably a better idea to simply define a function in C which B can run once after having imported C.
Upvotes: 0