[Tutor] scoping oddity

tanja pislar tanja.pislar at gmail.com
Sat May 7 16:18:42 CEST 2005


hi Michael,

in Python, names are not declared ahead of time so Python uses the
assigment of a name to "bind" it to a particular namespace.

you first assigned a "global" x with the value of 5.
in your testa and testc functions, you are only using variable x, and
because x is already assigned globaly, python sees it and uses it.
Meanwhile, in your function testb, you create a local x, assigning to
it a value (thus successfuly shadow the global x), but because the
assigment itself uses a refference to it, Python complains with a
UnboundLocalError: local variable 'x' referenced before assignment.

if you want to use the global x in your testb function, you should use
the global statement:
def testb(astr):
   global x
   x = x - 1
   print astr, x

regards,
tanja

On 5/7/05, Michael.Coll-Barth at verizonwireless.com
<Michael.Coll-Barth at verizonwireless.com> wrote:
> Good morning,
> 
> I came across a rather odd issue with scoping.  Can someone explain why
> testa and testc works, but not testb.  I am running under python 2.4.1 on
> Windows NT.
> 
> thanks,
> Michael
> 
> x = 5
> 
> def testa(astr):
>      print astr, x
> 
> testa(22)
> 
> def testb(astr):
>      x = x - 1
>      print astr, x
> 
> testb(22)
> 
> def testc(astr):
>      print astr, x-1
> 
> testc(22)
> ___________________________________________________________________
> The information contained in this message and any attachment may be
> proprietary, confidential, and privileged or subject to the work
> product doctrine and thus protected from disclosure.  If the reader
> of this message is not the intended recipient, or an employee or
> agent responsible for delivering this message to the intended
> recipient, you are hereby notified that any dissemination,
> distribution or copying of this communication is strictly prohibited.
> If you have received this communication in error, please notify me
> immediately by replying to this message and deleting it and all
> copies and backups thereof.  Thank you.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


-- 
www.klaustrofobik.org


More information about the Tutor mailing list