Carmen
Carmen

Reputation: 2873

Importing Parent Module and the Child Module

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?

Upvotes: 4

Views: 790

Answers (2)

Taymon
Taymon

Reputation: 25686

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')

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 994787

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.

Upvotes: 2

Related Questions