[Tutor] namespaces and global
kent37 at tds.net
Wed Oct 14 14:01:17 CEST 2009
On Wed, Oct 14, 2009 at 7:26 AM, Jose Amoreira <ljmamoreira at gmail.com> wrote:
> 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:
> Now I call my module function, expecting to get the triple of the argument I
> feed it with, but, instead, I get an error:
> 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.
Python 'global' variables are not really global (everywhere
accessible), they have module scope. So your function f() looks for
the name 'a' first in its local scope, then in the scope of its
containing module defs. It will not look in the namespace of the
caller unless it is also in defs.
> 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?
Why do you want to do this? One option is to pass locals() in to the
function. You can also access the caller's context through a stack
frame. But both of these are unusual.
More information about the Tutor