[Tutor] x is a global variable
spir
denis.spir at free.fr
Mon Nov 30 19:02:08 CET 2009
Hello Eike!
Eike Welk <eike.welk at gmx.net> dixit:
> 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
Well, this is certainly not specific to closures.
i = 0
def f():
i = i+1
print i
f()
==> UnboundLocalError
Imo, in this case, "i = i+1" is a kind of "paradoxal injonction" (lol! not sure of the exact idiom in english). You tell python both to create a local i (thus ignore any other scope to lookup for variables called 'i') and to use global i to define the local one.
If I were the victim of such a "paradoxal injonction" I would reply with a naughty word!
> ---
> Eike.
>
Denis
________________________________
la vita e estrany
http://spir.wikidot.com/
More information about the Tutor
mailing list