[Tutor] scoping oddity

Brian van den Broek bvande at po-box.mcgill.ca
Sat May 7 16:43:48 CEST 2005


Michael.Coll-Barth at VerizonWireless.com said unto the world upon 
2005-05-07 09:56:
> 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

<SNIP>

> def testb(astr):
>      x = x - 1
>      print astr, x

`x =', with a function def, gets interpreted as "create a new name x 
in the function-local scope and bind it to whatever is on the right of 
the `='. But, on the right is an expression involving x itself. You 
might expect Python to look to the global scope to find x, but by 
writing `x =', you've already settled that x will be a local scope 
name, so it looks only in the local scope. Of, course, when it gets to 
`x -1', x hasn't yet been given a reference and it all barfs.

HTH,

Brian vdB



More information about the Tutor mailing list