Code blocks

Alex Martelli aleaxit at yahoo.com
Mon Oct 13 18:34:54 EDT 2003


David Mertz wrote:
   ...
> So for that, I would suggest a new scopeless pseudo-function syntax.
> E.g.:
> 
>     block foo(this, that, other):
>         x = this+that
>         y = this*other
>         z = x // (y-that)
> 
> Using this is like a function, but the names wind up in the calling
> namespace:

Calling rather than defining?  For some reason this seems strange
to me.  Maybe it's just the vague memory of dynamic scoping being
a rather bad thing, but aren't there more use cases for affecting the
defining scope (which you DO know intimately when you're defining)
than for defining the calling scope (which in general you'd treat as a
black box?

>     def bar(someblock):
>         a, b, c = (4, 5, 6)
>         someblock(a,b,c)
>         return x,y,z
> 
>     vals = bar(foo)   #-> (9, 24, 0)
> 
> That is, I have no desire for blocks to be nameless, just for them to be
> passable as first class objects.

Yes, renouncing namelessness could perhaps be a reasonable compromise.
But let's consider use cases -- e.g. a "with this file" HOF.  If a block's
variables were in the _defining_ scope, I could change the current:

def blahblah(filename):
    f = open(filename)
    try:
        x = someprocessingwith(f)
        y = somemorewith(f)
    finally:
        f.close()
    # proceed, using x and y

into:

def blahblah(filename):
    block computexy(f):
        x = someprocessingwith(f)
        y = somemorewith(f)
    do_with_file(filename, computexy)
    # proceed, using x and y

using do_with_file as a black-box HOF, though it would typically be

def do_with_file(filename, thecallable):
    f = open(filename)
    try:
        return thecallable(f)
    finally:
        f.close()

and similarly for doing things while holding a lock, etc, etc.  Basically,
the kind of things you do with code-block passing in Smalltalk, Ruby &c.

What different set of interesting use-cases would be enabled by
having the block's apparently-local variables live in the namespace
of the caller rather in that of the definer?


Alex





More information about the Python-list mailing list