python first assignment of a global variable

Emile van Sebille emile at fenx.com
Wed Jul 15 14:14:57 EDT 2009


On 7/15/2009 10:55 AM Rodrigue said...
> I came accross a strange behaviour in python today. Here is a simple
> example to describe my situation:
> 
> MY_GLOBAL = ''

<snip>

> def e_raise():
>     if not MY_GLOBAL:
>         MY_GLOBAL = 'bla'
> 

<snip>

> Traceback (most recent call last):
>   File "glo.py", line 49, in <module>
>     e_raise()
>   File "glo.py", line 39, in e_raise
>     if not MY_GLOBAL:
> UnboundLocalError: local variable 'MY_GLOBAL' referenced before
> assignment

the def prepares the function for subsequent use.  At this prep time, 
MY_GLOBAL, by virtue of being assigned to later in the function, and the 
absence of a global statement, is identified as a local variable. 
Later, at execution time, testing MY_GLOBAL fails as it's not yet been 
assigned to.

HTH,

Emile




More information about the Python-list mailing list