Python vs. Io

John Roth newsgroups at jhrothjr.com
Thu Jan 29 16:32:10 EST 2004


"Daniel Ehrenberg" <LittleDanEhren at yahoo.com> wrote in message
news:711c7390.0401291301.3f95794 at posting.google.com...

> Can anyone show me how to so much as alias "for" to "each" in Python

Without getting into the language wars, I think what you're looking
for is called the Visitor Pattern (Design Patterns: GOF). It's actually
trivial to implement as long as you're not looking for built-in support.

Something like this works quite well in any object where you want
to implement a visitor over a collection:

class aCollection:
    def visit(self, instance):
        for x in self._collection:
            instance.visitor(x)
        return instance.result()

The final call is a little more than the bare visitor pattern, but it
allows the visitor instance to pass back a result so you can use
it in expressions.

A visitor then looks like this:

class fubar:
    def __init__(self):
        self.whatever = 0
    def visitor(self, value):
        self.whatever += value
    def result(self):
        return self.whatever

and you use it like this:

ohWow = aCollection.visit(fubar())

Unlike a block in, for example, Ruby, a visitor instance
can be pre-initialized, it can have multiple methods and
it can persist after being passed against the collection.

Of course, you can use more complex data structures as well,
see the compiler stuff for examples of the visitor pattern used
over the Python Abstract Syntax Tree.

The visitor pattern is also very useful for file system
navigation; I use it consistently.

John Roth

>
> Daniel Ehrenberg





More information about the Python-list mailing list