[Tutor] python closures

spir denis.spir at free.fr
Mon Nov 30 22:00:12 CET 2009


Eike Welk <eike.welk at gmx.net> dixit:

> On Monday 30 November 2009, Hugo Arts wrote:
> > Consider this python session:  
> >  >>> x = 0
> >  >>> def f():  
> >
> > 		x = x + 1
> >  
> >  >>> f()  
> >
> > Traceback (most recent call last):
> >   File "<pyshell#27>", line 1, in <module>
> >     f()
> >   File "<pyshell#26>", line 2, in f
> >     x = x + 1
> > UnboundLocalError: local variable 'x' referenced before assignment  
> Ah... what a pity I didn't try this. I used similar code in my 
> response to Spir and thought it would be somehow connected to 
> closures. Sending nonsense statements to the list again... 

My answer was stupid as well. Actually, guess I hadn't understood the real sense of Hugo's comment... until I tried to answer your post, Eike.

Denis

PS:
I just found by chance an article (actually a pair of) by Paul Graham (Lisp advocate) that really show how pitifully helpless python is (I'm half joking) compared to "Lisp/Perl/Smalltalk/Javascript".
http://www.paulgraham.com/icad.html (see end of article)
http://www.paulgraham.com/icadmore.html (search Paul Prescod's reply)

Quote:
<< I was actually surprised at how badly Python did. I had never realized, for example, that a Python lambda-expression  couldn't contain the same things as a named function, or that *variables from enclosing scopes are visible but not modifiable*. Neither Lisp nor Perl nor Smalltalk nor Javascript impose either restriction. >>
(I highlight)

Please don't take my quoting as an occasion for flamewar -- I'm just quoting to bring an external point of view into the thread. 

An interesting thing he points earlier is that (provided anonymous funcs were real funcs and changing external vars were possible) python,'s idiom for his example would not be:

def accum(n):
   lambda i: n += i

but instead:

def accum(n):
   return lambda i: return n += i

But actually he's wrong, I guess, it would even be:

def accum(n):
   return lambda i: n += i ; return n

(cannot return a statement) 

Denis
________________________________

la vita e estrany

http://spir.wikidot.com/



More information about the Tutor mailing list