[Python-Dev] Re: anonymous blocks

Fredrik Lundh fredrik at pythonware.com
Wed Apr 20 08:47:51 CEST 2005


Josiah Carlson wrote:

> See the previous two discussions on thunks here on python-dev, and
> notice how the only problem that seem bettered via blocks/thunks /in
> Python/ are those which are of the form...
> 
> #setup
> try:
>     block
> finally:
>     #finalization
> 
> ... and depending on the syntax, properties.  I once asked "Any other
> use cases for one of the most powerful features of Ruby, in Python?"  I
> have yet to hear any sort of reasonable response.
> 
> Why am I getting no response to my question?  Either it is because I am
> being ignored, or no one has taken the time to translate one of these
> 'killer features' from Smalltalk or Ruby, or perhaps such translations
> show that there is a better way in Python already.

for my purposes, I've found that the #1 callback killer in contemporary Python
is for-in:s support for the iterator protocol:

instead of

    def callback(x):
        code
    dosomething(callback)

or with the "high-level intent"-oriented syntax:

    dosomething(**):
        def libraryspecifiedargumentname(x):
            code

I simply write

    for x in dosomething():
        code

and get shorter code that runs faster.  (see cElementTree's iterparse for
an excellent example.  for typical use cases, it's nearly three times faster
than pyexpat, which is the fastest callback-based XML parser we have)

unfortunately,

    def do():
        print "setup"
        try:
            yield None
        finally:
            print "tear down"

doesn't quite work (if it did, all you would need is syntactic sugar for "for
dummy in").

</F>

PS. a side effect of the for-in pattern is that I'm beginning to feel that Python
might need a nice "switch" statement based on dictionary lookups, so I can
replace multiple callbacks with a single loop body, without writing too many
if/elif clauses.



More information about the Python-Dev mailing list