using modules

Terry Reedy tjreedy at udel.edu
Mon Sep 6 21:21:55 CEST 2010


On 9/6/2010 12:55 PM, Sal Lopez 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.

Python code execute within the context of the builtin namespace, a 
module namespace (misleadingly called 'globals'), a local namespace (the 
same as the module namespace for top-level code), and for nested 
functions, intermediate namespaces.

"import defs" binds the name 'defs' to the module object. Code in the 
defs module still executes within the defs context where it is defined. 
This is lexical name resolution. The same is still true if you import 
the function with "from defs import make_sound".

What you were expecting is dynamic name resolution, where names are 
resolved within the calling context rather than the definition context. 
I believe this is dynamic scoping. This has been tried in other 
languages. For more, try
https://secure.wikimedia.org/wikipedia/en/wiki/Dynamic_scoping

-- 
Terry Jan Reedy




More information about the Python-list mailing list