Named code blockes

James_Althoff at i2.com James_Althoff at i2.com
Mon Apr 23 14:55:44 EDT 2001


Alex Martelli wrote:

Is it so 'costly' to give these statement suites a name?

<jima>
I think it is.  In Smalltalk, for example, you can write
something like (approx.):

collection do: [:item | item doThis. item doThat]

This passes an arbitrary and unnamed block of code to
the collection object for executing.

in Python this would be:

def doThisAndDoThatToItem(item):
    item.doThis()
    item.doThat()

collection.do(doThisAndDoThatToItem)

Now suppose the call to collection.do(xxx) is in the middle of a
very long class def.  Then I have to put the doThisAndDoThatToItem
def before the class or after the class thereby separating the definition
from its one and only use by possibly hundreds of lines of
code.  This is not nice for readability.  Or I have to define
doThisAndDoThatToItem
as a method in my class which clutters my class with an unnecessary
method.  Or I have to resort to extracting the items of the
collection for use in a for loop (for example) which means the collection
must be written in such a way as to expose its items as a sequence
(which the collection writer might not have wanted to do).

Unnamed blocks are a very powerful programming device.  As far as I can
tell, the main reason that Python does not support them is that no one
has figured out how to handle the indentation issues -- the syntax thing ;
-)
</jima>


I generally find that turning a lambda into a (named) local
function makes my code clearer in all but the most trivial
cases -- if that applies to expressions, it should a fortiori
apply to suites.


> (imo, nested scopes are pretty useless without real blocks)

I'm not so hot about nested scopes, but, anyway, we DO have
'real' blocks -- surely, giving them a name doesn't take
their reality away, does it?-)






More information about the Python-list mailing list