Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python determining name of the importing module

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?

like image 693
Charles Paxson Avatar asked Nov 19 '25 23:11

Charles Paxson


1 Answers

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.

like image 53
Alexey Kachayev Avatar answered Nov 22 '25 13:11

Alexey Kachayev