[Python-3000] Adaptation vs. Generic Functions
Tim Hochberg
tim.hochberg at ieee.org
Wed Apr 12 23:17:37 CEST 2006
Here's a little thought experiment:
What would happen if 'a+b' was just syntactic sugar for
'operator.add(a,b)', where operator.add was a generic
function, instead of the current magic dance involving
__add__ and __radd__.
Neglecting the fact that it would break all Python code now in
existence, would this be a good thing, a bad thing or can we even tell?
To get the current effect of __add__ and __radd__, class definitions
would look something like:
class Weeble:
#....
@operator.add.register(Weeble, object)
def add(a, b): #...
@operator.add.register(object, Weeble)
def radd(b, a): #...
That's not too different from today, although it is a little weird that
add and radd are outside of Weeble. One would also need to need to be
more flexible about strict dominance, allowing some sorts of ties and
trying the tied functions one at a time until one worked. (Hmmm...
perhaps this is the kind of thing Guido was referring to in his blog. If
so, it bounced off my thick head ;-)
I suppose one could add some metaclass magic to type so that __add__ and
__radd__ were picked up and registered as above. That would make things
look superficially the same as now and would be more or less backwards
compatible.
On the plus side, there's a lot more flexibility. You could teach two
types that don't know anything about each other how to play nice
together simply by registering a couple more adapters to operator.add.
On the minus side, there's perhaps too much flexibility. Any function
call or module importation or even attribute access could suddenly
change the behaviour of an unrelated type.
>>> a = 1
>>> b = 2
>>> # this calls operater.add.register(int,int)(lambda a,b:str(a+b))
>>> c = frobulate()
>>> a + b
"3"
We're all consenting adults here, so should I even worry about this. I
don't know.
I suspect this falls into the "wild ideas' category, but it's an
interesting thought experiment anyway. Perhaps with relevance to other
uses of generic functions.
Regards,
-tim
More information about the Python-3000
mailing list