4

I am testing have 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 not defined. To make this work, I need to do 'import os' in the test script.

What I don't understand is that I already imported hello.py which imported os already. Shouldn't the test script know that by importing hello.py, it is has already imported os?

asked Feb 26, 2012 at 3:06

2 Answers 2

3

It does import os, but the reference to the os module is in the namespace of the hello module. So, for instance, you could write this in your test script:

import hello
print hello.os.listdir('/tmp')
answered Feb 26, 2012 at 4:04
Sign up to request clarification or add additional context in comments.

1 Comment

This gets to the heart of the question, which is about the handling of namespaces. But it should be added that this is not a good way to access a system module: it suggests that os is somehow part of hello, which can lead to real confusion in non-toy cases. Importing os twice is the way to go.
2

No, Python modules do not work this way. By using import to import one module into another's namespace, you set up the name of the imported module in the calling module's namespace. This means you generally don't want to use that same name for any other purpose within the calling module.

By hiding the import os inside the module, Python allows the calling script (the test script in your case) to decide what it wants to import into its own namespace. It's possible for the calling script to 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 is only loaded once. The only question that remains is the visibility of the name os inside each module. There is no (well, negligible) performance implication for importing the same module more than once. The module initialisation code is only run the first time the module is imported.

answered Feb 26, 2012 at 3:11

1 Comment

When you say that 'os' module is only loaded once, so in my case when the test script tries to do an 'import os', then does it mean that it is just going to "reference" the loaded 'os' module?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.