Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python import type detection

Can a python module detect if has been imported with import module or from module import *? Something like

 if __something__=='something':
      print 'Directly imported with "import ' + __name__ + '"'
 else:
      print 'Imported with "from ' + __name__ + ' import *"'

Thank you.

like image 470
Emilio Avatar asked Mar 15 '26 02:03

Emilio


1 Answers

No, it's not possible to detect this from within the module's code. Upon the first import, the module body is executed and a new module object is inserted in sys.modules. Only after this, the requested names are inserted into the namespace of the importing module.

Upon later imports, the module body isn't even executed. So if a module is first imported as

import module

and a second time as

from module import name

it has no chance to do anything at all during the second import. In particular, it cannot check how it is imported.

like image 66
Sven Marnach Avatar answered Mar 16 '26 15:03

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!