High Order Messages in Python

Mike Meyer mwm at mired.org
Sat Oct 22 19:22:34 EDT 2005


"eduardo.padoan at gmail.com" <eduardo.padoan at gmail.com> writes:

> I'm reading about "high order messages" in Ruby by Nat Pryce, and
> thinking if it could be  util and if so, if it could be done in Python.
> Someone already tried?

Yes, I'm pretty sure it could be done in Python. All it really needs
is the ability to catch references to undefined attributes, which
Python has. You make the HOM of your collection class return an object
with a reference to self, and the __getattr__ method of that classs
then invokes getattr on each object in the referenced collection
instance for the undefined method, manipulating the result as
appropriate for that HOM, and returning a new list.

But this really isn't a very good fit for Python. This is really a
feature for more aggressively OO languages. To make the examples HOMs
described really useful, you want to add them to some base class for
collections. But that base class doesn't exist in Python - Python just
isn't that OO.

You could add various HOMs to lists, tuples, generators and iterators
- but then anyone who wanted to create a new sequence class would have
to add all of the HOMs that their clients might want to use. The
pythonic way would be to add a function that works with all the
various sequence types - which would then automatically work with any
user-defined classes that quacked like a sequence. It's not very OO -
but it is pythonic. In fact, Python already has functions that capture
the functionality of the example HOMs in the links you posted: where
and unless are handled by filter. in_order_of and in_reverse_order_of
are handled by sorted. do is is handled by map. Of course, recent
versions of python provide list comprehensions as preferable to some
of these functions.

That said, HOM's are a *very* powerful mechanism. The examples - and
my discussion of them - cover just one very broad use case. There may
be others where they are a better fit with Python. Having examples of
how to do these kinds of things around is probably worthwhile.

    <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list