Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

using modules

0 views
Skip to first unread message

Sal Lopez

unread,
Sep 6, 2010, 12:55:03 PM9/6/10
to pytho...@python.org
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.

Richard Thomas

unread,
Sep 6, 2010, 2:17:34 PM9/6/10
to

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.

Terry Reedy

unread,
Sep 6, 2010, 3:21:55 PM9/6/10
to pytho...@python.org

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

0 new messages