Code block literals

Mike Rovner mike at nospam.com
Wed Oct 8 18:56:33 EDT 2003


Dave Benjamin wrote:
> Dave Benjamin wrote:
>
>>  >>> print mylist.map({ |x| return x + 2 }, range(5))
>> 0, 2, 4, 6, 8
>
> Duh... sorry, that should read:
> print range(5).map({ |x| return x + 2 })

I either case it will be [2, 3, 4, 5, 6]  :)

Instead of lambda use list comprehensions:

print [x+2 for x in range(5)]

Unnamed code blocks considered evil :), use named instead (functions).

With nested scopes you can do amazing things. I myself was used to code
blocks due to perl background, but python idiom are not worse to say the
least.
For example:

class C(object):
   ...
   def aprop():
       def reader(self): return 0
       def writer(self,newval): pass
       return reader, writer
   aprop=property(aprop())


Mike








More information about the Python-list mailing list