[Edu-sig] Re: ..., closures, ... other weirdness

Dethe Elza dethe.elza at blastradius.com
Tue Jan 27 01:21:13 EST 2004


>> Of course this method returns a string instead of printing the 
>> message.
>> If you want to print the message you need to, def anon(x):
>> because print is not a valid lambda expression (why?, I don't know):

Lambdas are limited to a single expression by design.  It would be nice 
if there was an alternate form of "def" which returned an anonymous 
function :

anon = def(x,y): return x + y

But Python doesn't work that way (Javascript "function" does).

> Here's something else I learned about Python recently.  This is weird,
> non-idiomatic stuff:  a pseudo-generator (of sorts) using function
> attributes:
[snip]
>>>> def weird(x=1,y=1):	
>          '''List consecutive Fibonacci numbers per each call'''
>          try:     weird.x
>          except:	weird.x = x
> 	   try:     weird.y
> 	   except:  weird.y = y
> 	   weird.x, weird.y = weird.y, weird.x + weird.y
> 	   return weird.x
>
>>>> wi = iter(weird,89)   # note:  no "initialization" of weird needed
>
>>>> for i in wi:  print i,
>
>  1 2 3 5 8 13 21 34 55

While function attributes are indeed cool (and weird), I'd probably use 
them more if they didn't need to know their own name (i.e., if there 
was something like "self" which means "this is me, the function" from 
within functions.

On the other hand, your example is probably simpler as a genuine, 
iterable, generator:

def weird():
   x,y = 1,1
   while True:
     yield x
     x,y = y, x+y

from itertools import islice
wi = islice(weird(), 20)
for i in wi: print i,

We use islice to prevent iterating forever, as this will happily give 
you every fibonnacci number until the end of time otherwise.

--Dethe

"Ambiguity, calculated or generative, as a means of discontinuous 
organization, at first seems familiar to us"
-- Pain Not Bread, An introduction to Du Fu




More information about the Edu-sig mailing list