[Tutor] x is a global variable
Eike Welk
eike.welk at gmx.net
Mon Nov 30 18:09:38 CET 2009
Hello Spir!
On Monday 30 November 2009, spir wrote:
> which seems to indicate python really embeds "symbolic references"
> (*) to outer *variables*, when creating a closure for g0. Not
> "pointer references" (**), otherwise the replacement of x would not
> be seen by the closure --like in the case of default-parameter.
> Actually, I find this _Bad_. Obviously, the func's behaviour and
> result depend on arbitrary external values (referentially opaque).
If I understand you right, you are proposing that the inner function
g0 should get a separate copy of the global namespace. The copy should
be done when the function is defined.
When this would be implemented, inner functions (g0) would be treated
very differently from outer functions (f), with respect to global
variables. I would not like this different treatment. When a global
variable is changed all functions should see the change.
I think currently there are three 'containers' where functions can
find variables in Python:
- local variables
- the closure, which is empty in outer functions (f.func_closure)
- global variables, this is probably f.__module__.__dict__.
The exact semantics of closures seem to be a bit tricky. Below is some
behavior I find surprising. I had expected that a local variable 'i'
is created in function 'inc'. Instead the function fails with an
error. (Producing the error is IMHO surprising, but sane behavior.):
In [25]:def clos():
i = 0
def inc():
i = i + 1
print i
def pri():
print i
return inc, pri
In [33]:inc, pri = clos()
In [34]:pri()
0
In [35]:inc()
-------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
/home/eike/<ipython console> in <module>()
/home/eike/<ipython console> in inc()
UnboundLocalError: local variable 'i' referenced before assignment
---
Eike.
More information about the Tutor
mailing list