Ian Bicking: the old part of his blog

First try at generic functions comment 000

At work we've been using:

@jsonify.when(Binary)
...

-Chris

Comment on Re: First Try at Generic Functions
by Chris L

Comments:

That only works with @dispatch.on, not @dispatch.generic, unless you use a dispatch.strategy.PositionalSignature with a sequence of classes, not a single class. E.g.:

from dispatch.strategy import PositionalSignature

@jsonify.when(PositionalSignature([Binary]))
def jsonify(ob):
    # ...

As you can see, this is more trouble than it's worth, unless you're writing code that dynamically adds methods and doesn't want to have to do string manipulation:

def register_jsonifier(cls, func):
    @jsonify.when(PositionalSignature([cls]))
    def foo(ob): return func(ob)

However, because of the way condition strings are interpreted, you could just as easily write:

def register_jsonifier(cls, func):
    @jsonify.when("isinstance(ob,cls)")
    def foo(ob): return func(ob)

Because the reference to cls is resolved immediately and treated as a constant thereafter. So it's really pretty rare that you'd want to delve into the object-based interface to the criteria system.

# Phillip J. Eby