On 30 July 2010 11:39, Nick Coghlan <ncoghlan@gmail.com> wrote:
On Fri, Jul 30, 2010 at 8:46 AM, Éric Araujo <merwok@netwok.org> wrote:
> Thank you for explaining generic functions so clearly.
> Is there a good module out there implementing them without “crazily
> complex overloading schemes”?

I'm not sure. Most of my exposure to generic functions is through PJE
and he's a big fan of pushing them to their limits (hence RuleDispatch
and PEAK-rules).

There is an extremely bare bones implementation used internally by
pkgutil's emulation of the standard import process, but Guido has said
we shouldn't document or promote that in any official way without a
PEP (cf. the simple proposal in http://bugs.python.org/issue5135 and
the PJE's previous more comprehensive proposal in PEP 3124).

As others have explained more clearly than I did, generic functions
work better than magic methods when the same basic operation (e.g.
pretty printing, JSON serialisation) is common to many object types,
but the details may vary between applications, or even within a single
application. By giving the application more control over how different
types are handled (through the generic functions' separate type
registries) it is much easier to have context dependent behaviour,
while still fairly easily sharing code in cases where it makes sense.

E.g. to use Alex Gaynor's example of attendee list serialisation and
the issue 5135 syntax:

def json_unauthenticated(obj):
   return json.dumps(obj) # Default to a basic dumps() call

def json_authenticated(obj):
   return json_unauthenticated(obj) # Default to being the same as
unauthenticated info

def attendee_titles(attendees):
   return json.dumps([attendee.title for attendee in attendees])

def attendee_details(attendees):
   return json.dumps([attendee.full_details() for attendee in attendees])

I really like Alex Gaynor's simple MultiMethod implementation. From:


It doesn't have a concept of a default call, but that would be very easy to add. Basic usage is:

json_unauthenticated = MultiMethod()

def json_unauthenticated(attendees):
    return json.dumps([attendee.title for attendee in attendees])

def json_unauthenticated(othertypes):
    return json.dumps(othertypes)

And so on.


(Keep in mind that I don't use JSON, so there are likely plenty of
details wrong with the above, but it should give a basic idea of what
generic functions are designed to support).


Nick Coghlan   |   ncoghlan@gmail.com   |   Brisbane, Australia