[Tutor] namespaces and global

Jose Amoreira ljmamoreira at gmail.com
Wed Oct 14 13:26:22 CEST 2009

I'm new to this list. I tried to find the answer to my question but found 
nothing I could really use. I'm sorry if this is a FAQ.

I want to use a variable defined in an interactive session with the python 
interpreter inside a function imported from a module.

For instance, imagine that my module (call it defs.py, for instance) consists 
def f(x):
    return a*x

In an interactive session, I import my module:
>>> from defs import f
and I define a global variable a:
>>> a=3
Now I call my module function, expecting to get the triple of the argument I 
feed it with, but, instead, I get an error:
>>> f(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "defs.py", line 3, in f
    return a*x
NameError: global name 'a' is not defined

I tried using the global command in the module, both before the function 
definition and inside the function definition, but none worked as I expected.
Of course I could redefine my module function, including the parameter a in 
the list of arguments, but I'd rather not.

So, my question: is there any way of telling the interpreter to use the value 
of parameters defined in the interactive session when computing the value of a 
module function?

More information about the Tutor mailing list