Modifying a variable in a non-global outer scope?

bruno at modulix onurb at xiludom.gro
Fri May 19 21:24:27 CEST 2006


Edward C. Jones wrote:
> #! /usr/bin/env python
> """
> When I run the following program I get the error message:
> 
> UnboundLocalError: local variable 'x' referenced before assignment
> 
> Can "inner" change the value of a variable defined in "outer"? 

Not this way

> Where
> is this explained in the docs?

IIRC,
http://www.python.org/doc/2.4.2/ref/naming.html

> """
> def outer():
>     def inner():
>         x = x + 1
>
>     x = 3
>     inner()
>     print x
> 
> outer()

What are functions arguments and return values for ?

def outer():
  def inner(x):
     return x+1
  x = 3
  x = inner(x)
  print x

outer()

Using side-effects - specially this way - is a Very Bad Thing(tm). It
makes code that is hard to read and hard to maintain.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list