[Q] Bug in Python?

Brian Quinlan brian at sweetapp.com
Thu Mar 15 02:29:43 EST 2001


Sorry, but you missed a pretty subtle Pythonism :-)

When Python examines the code block for the function 'a', it sees that 'var'
is being assigned a value without having been declared global. It therefore
considers it to be a local variable and then throws an exception when you
print 'var' because you are printing a variable that has not (yet) been
assigned a value. The relevant part of the python language reference
follows:

"The global statement is a declaration which holds for the entire current
code block. It means that the listed identifiers are to be interpreted as
globals. While using global names is automatic if they are not defined in
the local scope, assigning to global names would be impossible without
global."

So, you might want to change your code to:

############# test.py ###############
var = None

def a():
    global var
    print var # No exception anymore
    if var != None:
        var = None  # >> pass isn't useful anymore

def b():
     print var
     a()

b()
#################################

Cheers,
Brian

-----Original Message-----
From: python-list-admin at python.org
[mailto:python-list-admin at python.org]On Behalf Of Daehyok Shin
Sent: Wednesday, March 14, 2001 10:16 PM
To: python-list at python.org
Subject: [Q] Bug in Python?


Recently, I met a strange behavior of Python 6.1.
When I tried the following module,
I got an error message in "print var":
    UnboundLocalError: var

But, when I changed "var=None" to "pass",
the error message was gone and I got an expected result:--printing None and
None.
What happens here? Is this a bug in Python or I missed something?

############# test.py ###############
var = None

def a():
     print var #UnboundLocalError
     if var != None:
          var = None  # >> pass

def b():
     print var
     a()

b()
#################################

--
Daehyok Shin (Peter)
Terrestrial Hydrological Ecosystem Modelers
Geography Department
UNC-CH


--
http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list