Python import type definition

Can a python module detect if it was imported with import moduleor from module import *? Sort of

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

Thank.

+3
source share
2 answers

No, this cannot be detected from the module code. After the first import, the module body is executed, and a new module object is inserted into sys.modules. Only after that the requested names are inserted into the namespace of the import module.

At subsequent import, the module body is not even executed. Therefore, if the module is first imported as

import module

and second time like

from module import name

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

+4
source

Svens, , , . , , .

, , , . script unit test, , .

import sys

def myfunction(blah):
    return "something like: " + blah

noargs=len(sys.argv)
if noargs>1:
    for i in range(noargs-1):
        print myfunction(sys.argv[i+1])

, , , .:)

0

All Articles