[Tutor] python closures

Stefan Behnel stefan_ml at behnel.de
Mon Nov 30 16:17:26 CET 2009


spir, 30.11.2009 11:24:
> Below startup definitions:
> 
> x = 1
> 
> def f():
>   n = 1
>   def g0(a):
>     print (x + n + a) 
>   return g0
> 
> I'm surprised the snippet below works as expected (py 2.6) without any trick:
> 
> g = f()
> g(1)	# --> 3
> 
> This means a (real) closure is built for g0, or what?

Yes.


> Thought I would need instead to use the old trick of pseudo default-parameters:
> 
> def f():
>   n = 1
>   def g0(a, n=n, x=x):
>     print (x + n + a) 
>   return g0
> 
> to let the inner func g0 "remember" outer values. Why is this idiom used, then? Has something changed, or do I miss a relevant point?

Different use case. The above uses default arguments for n and x that can
be overridden by callers, but that have a value if callers do not pass
them. Values in closures can only be modified by the owner(s) of the names
that participate in the closure (i.e. the function f in this case).


> The bit below also works:
> 
> x = 2
> ...
> g(1)	# --> 4

x is not in the closure, it's a global name.


> the func's behaviour and result depend on arbitrary external values (referentially opaque). What do you think?

It's a matter of how you use it. Closures make a lot of sense for many
cases, but there are certainly also cases where using them feels like a
goto - just like global variables.

Stefan



More information about the Tutor mailing list