using modules

Richard Thomas chardster at gmail.com
Mon Sep 6 20:17:34 CEST 2010


On Sep 6, 5:55 pm, Sal Lopez <sal_lo... at me.com> wrote:
> 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.              

The make_sound function has two scopes in which to resolve the name
'sounds' the first is its local scope i.e. the scope of things defined
in the function itself but that just contains 'animal'. The second is
its global scope which is another name for its module's namespace. In
this case that's the namespace of the 'defs' module. The namespace of
the main module (the module that you ran), is separate. You could do
this:

import defs
defs.sounds = {'cat': 'meow', ... }

Or even:

#defs.py
sounds = {}

#main.py
import defs
defs.sounds.update({'cat': 'meow', ... })

Regards,
Richard.



More information about the Python-list mailing list