[Tutor] global
Jeff Shannon
jeff@ccvcorp.com
Thu Jul 31 21:59:03 2003
Kirk Bailey wrote:
> Got a script that wants to bark. Early in the program I define some
> defaults for certain variables to define state (they are used as
> boolian flags, 1/0 stuff). Later, a function referrs o one- and barks.
> Says it does not know the variable- undefined. Hmmm, sure it is...
> Apparently this function is not aware the variable is already defined.
> How do I force a variable to be global so it will automatically be
> available to the insiode structure of a defined function without
> having to formally pass it as an arguement?
Presuming that this is within the same module, nothing needs to be done.
However, rebinding a name that [supposedly] points to a global object
can result in a problem like what you mention --
>>> spam = 5
>>> def foo(value):
... print "Had %d spam," % spam
... spam = value
... print "Now have %d spam" % spam
...
>>> foo(6)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 2, in foo
UnboundLocalError: local variable 'spam' referenced before assignment
>>> spam
5
>>>
Since there is an assignment to spam within the function foo(), spam
becomes a local variable. Because of certain optimizations used for
local variables, this means that if spam isn't found in the locals()
[psuedo-]dict, it won't get looked up in the globals() dict. As a
result, attempting to access spam before assigning to it causes an error
-- Python knows that it should be a local, but can't find it there.
This can be resolved by placing the statement 'global spam' at the top
of foo(). That tells Python that this *isn't* a local variable, and
that it should always be looked for in the globals() dict.
If this isn't what's happening to you, then post the relevant code (the
module-level definitions and the function that's using them) and the
full traceback of the error.
Jeff Shannon
Technician/Programmer
Credit International