[Q] Bug in Python?

John W. Baxter jwbnews at scandaroon.com
Thu Mar 15 03:13:38 EST 2001


In article <t6Zr6.92712$__6.18256422 at typhoon.southeast.rr.com>,
 "Daehyok Shin" <DSHIN at nc.rr.com> wrote:

> 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()

> 

You're getting the unbound local error because, with the var = None 
form, the 
   print var
is indeed trying to print an unbound local variable.  var is a local 
because it is assigned to in a() but that hasn't happened by the time 
print needs to use it.  When you substitute the pass, then var becomes a 
global variable.  If you want to use the (module) global var in a() with 
the assignment to var, declare var global:

    global var

  --JOhn

-- 
John W. Baxter   Port Ludlow, WA USA  jwbnews at scandaroon.com



More information about the Python-list mailing list