Code block literals

Dave Benjamin dave at 3dex.com
Wed Oct 8 19:23:06 EDT 2003


Mike Rovner 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]  :)

Yeah yeah yeah, I really should read what I write before I post. But you 
know what I mean, damnit! =)

> Instead of lambda use list comprehensions:
> 
> print [x+2 for x in range(5)]
> 
> Unnamed code blocks considered evil :), use named instead (functions).

Why are they evil? Does being anonymous automatically make you evil?

For instance, I always thought this was a cooler alternative to the 
try/finally block to ensure that a file gets closed (I'll try not to 
mess up this time... ;) :

open('input.txt', { |f|
     do_something_with(f)
     do_something_else_with(f)
})

Rather than:

f = open('input.txt')
try:
     do_something_with(f)
     do_something_else_with(f)
finally:
     f.close()

Now, I suppose you could always do:

def with_open_file(filename, func):
     f = open(filename)
     try:
         func(f)
     finally:
         f.close()

# ...

def thing_doer(f):
     do_something_with(f)
     do_something_else_with(f)
with_open_file('input.txt', thing_doer)

But the anonymous version still looks more concise to me.

> 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())

Yeah, wasn't something like that up on ASPN? That's an interesting 
trick... are you sure it's not supposed to be "property(*aprop())" 
though? (who's being pedantic now? =)

Dave





More information about the Python-list mailing list