Import Parent Module and Child Module

I am testing this module called hello.py.

#!/usr/bin/python import os class hello(): def say(self): print "Hello" 

And I have this test script.

 #!/usr/bin/python import hello print os.listdir( '/tmp' ) 

The test script complains that 'os' is undefined. To do this, I need to do an os import in a test script.

I do not understand that I already imported hello.py, which imported os already. If the test script doesn’t know that by importing hello.py, has it imported os already?

+4
source share
2 answers

It imports os , but the link to the os module is in the namespace of the hello module. So, for example, you can write this in your test script:

 import hello print hello.os.listdir('/tmp') 
+3
source

No, Python modules do not work this way. Using import to import one module into another namespace, you configure the name of the imported module in the namespace of the calling module. This means that you generally do not want to use the same name for any other purpose in the calling module.

By hiding import os inside the module, Python allows a script call (a script test in your case) to decide what it wants to import into its own namespace. Perhaps the caller of the script say os = "hello world" and use it as a variable that has nothing to do with the standard os module.

It is true that the os module loads only once. All that remains is the question of the visibility of the name os inside each module. To import the same module more than once, there is no (well, negligible) performance. The module initialization code is launched only at the first input of the module.

+2
source

Source: https://habr.com/ru/post/1398438/


All Articles