[Edu-sig] Re: ..., closures, ... other weirdness
Kirby Urner
urnerk at qwest.net
Mon Jan 26 20:10:01 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):
Yes, right.
Plus you'll also need to define anon if you want your closure to consist of
more than one line of code (li'l lambda is just for one-liners).
> Closures are cool,
> Thanks,
> Jeff Sandys
Here's something else I learned about Python recently. This is weird,
non-idiomatic stuff: a pseudo-generator (of sorts) using function
attributes:
>>> def weird():
'''List consecutive Fibonacci numbers per each call'''
weird.x, weird.y = weird.y, weird.x + weird.y
return weird.x
>>> weird.x = 1
>>> weird.y = 1
>>> for i in range(8): print weird(),
1 2 3 5 8 13 21 34
But wait, there's more:
You can wrap this function with iter(callable, sentinel) to make it an
iterable:
>>> weird.x = 1
>>> weird.y = 1
>>> wi = iter(weird,89)
>>> for i in wi: print i,
1 2 3 5 8 13 21 34 55
So I guess in Python 2.4 we'll be able to go:
>>> weird.x = 1
>>> weird.y = 1
>>> wi = reversed(iter(weird,89))
>>> for i in wi: print i,
55 34 21 13 8 5 3 2 1
And now, to round out this little detour into arcane Python, let's make
weird() self-initializing, i.e. we don't want to have to assign weird.x and
weird.y before first use:
>>> 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
Weird.
Kirby
More information about the Edu-sig
mailing list