Carrying variables over from function to function
Peter Otten
__peter__ at web.de
Tue Sep 27 04:47:26 EDT 2005
Bruno Desthuilliers wrote:
> 2/ functional solution:
> -----------------------
> def make_funcs():
> x = 0
> def _abc():
> x = 1
> return x + 1
> def _abcd():
> return x + 1
> return _abc, _abcd
>
> abc, abcd = make_funcs()
> print abc()
> print abcd()
The x in function _abc() is not the same as that in make_funcs() and _abcd()
as you can easily verify by modifying _abc() to
def _abc():
x # raises UnboundLocalError
x = 1
return x + 1
Once a variable is assigned a value the compiler treats it as local to that
function. Closed-over variables are therefore always read-only, much to the
chagrin of Lisp-lovers.
Peter
More information about the Python-list
mailing list