Namespaces, classes, and using standard modules

Dan Rawson daniel.rawson.take!this!out! at asml.nl
Wed Aug 13 09:25:04 EDT 2003


I have several simple classes which need to us "standard" modules like os and sys

A class might look like:

# --------- MyClass.py -----------------------
class MyClass:
     def __init__ (self):
         self.data = ''
         self.data2 = 'mydata'

     def show (self):
         print "Data is " + self.data
         print "Other data is " + self.data2
         print "Directory is " + os.getcwd()
# --------------------------------------------


If I do:

 >>> import os
 >>> from MyClass import MyClass
 >>> x = MyClass()
 >>> x.show()

it fails with

NameError: global name 'os' is not defined

However, if I put the 'import os' statement in MyClass.py, but OUTSIDE the class definition, it works fine.  I can also 
(obviously) put the import inside the class definition, then use 'self.os.getcwd()' but that seems to me to be 
needlessly complicated.

I would have expected that importing os from the interactive prompt would have worked, and that the 'import os' 
statement in MyClass.py would have been ignored.

Any comments or clues about how this SHOULD work would be appreciated!

TIA . . . .

Dan





More information about the Python-list mailing list