using modules

Sal Lopez sal_lopez at me.com
Mon Sep 6 12:55:03 EDT 2010


The following code runs OK under 3.1:

@filename=cats_and_dogs.py

#!/usr/bin/python

def make_sound(animal):
    print(animal + ' says ' + sounds[animal])

sounds = { "cat": "meow", "dog": "woof" }

for i in sounds.keys():
    make_sound(i)

# output:
# dog says woof
# cat says meow

When I move the def to it's own file to create a module, it barfs:

@filename= cats_and_dogs.py
#!/usr/bin/python

import defs

sounds = { "cat": "meow", "dog": "woof" }

for i in sounds.keys():
    defs.make_sound(i)

@filename=defs.py
def make_sound(animal):
    print(animal + ' says ' + sounds[animal])

Traceback (most recent call last):
File "./cats_and_dogs.py", line 11, in <module>
defs.make_sound(i)
File "defs.py", line 4, in make_sound
print(animal + ' says ' + sounds[animal])
NameError: global name 'sounds' is not defined


I thought that importing the function(s) made them local to the main program? Any assistance is appreciated.              



More information about the Python-list mailing list