[Tutor] python closures

Alan Gauld alan.gauld at btinternet.com
Mon Nov 30 18:38:12 CET 2009


"spir" <denis.spir at free.fr> wrote

> 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:

I'm not sure how else it could work.
x is a global name so the function must reference it.
n is a local name so it musdt evaluate it (it will disappear otherwise)
a is a parameter delivered at run time.

> This means a (real) closure is built for g0, or what?
> 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

I did wonder if you would need n=n but I didn't think you would need x=x.

Its an interesting example and I confess I don't fully understand how 
Python's
naming/reference rules are working here.

> 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?

I thought you might need to do it if n had been a parameter of f()... but
having tried it no, it works as above.

I look forward to the explanation.

Alan G. 




More information about the Tutor mailing list