[Python-3000] defop ?

Nick Coghlan ncoghlan at gmail.com
Wed Nov 22 14:55:27 CET 2006


Antoine wrote:
> Is "defop" useful?
> 
> Why wouldn't it be possible to enable special method lookup with this kind
> of syntax:
> 
> iter = generic_function()
> iter.lookup_special_method("__iter__")
> 
> And then the classical:
> 
> class Foo:
>     def __iter__(self):
>         pass

A major benefit of the defop syntax lies in the fact that the full Python 
module namespace is available to you for disambiguation of which operation you 
are referring to. So if module A defines an overloaded operation "snap" and 
module B define an overloaded operation "snap", that's OK, because "defop 
A.snap" and "defop B.snap" can be used to make it clear which one you mean.

The magic method namespace, on the other hand, is completely flat: there can 
be only one __snap__ magic method in a given Python application. If two 
different modules both want to use the same magic method name, you're out of 
luck because you can't use the module namespace to disambiguate which one you 
actually want to support (heck, you might even want to support both of them).

A second benefit of defop is that if you have a reference to a generic 
function then you can overload it. With magic methods, you can only overload 
it if you know the appropriate incantation (see the thread about correcting 
the fact that the incantation to overload bool in 2.x is __nonzero__ instead 
of __bool__ - with defop, it could be written simply as "defop bool(self):", 
and issue wouldn't need to rise).

Finally, the defop syntax means a typo will likely result in an exception when 
the class definition is executed instead of at some random later time. For 
example, the typo "def __getiten__(self, key):" will go completely undetected 
when a class definition is executed, but "defop operator.getiten(self, key):" 
would fail with an AttributeError.

That said, it doesn't *have* to be new syntax - an appropriate function 
decorator and a class decorator or metaclass to register the appropriate 
overloads also support this. defop just makes it easier to read and write.

Cheers,
Nick.


-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list