Behaviour-based interface/protocol implementation?

Alan Franzoni mailing at franzoni.eu
Tue Jan 25 10:32:19 EST 2011


On Tue, Jan 25, 2011 at 7:55 AM, Chris Rebert <clp2 at rebertia.com> wrote:
> Not true actually:
>
> Python 2.7.1 (r271:86832, Dec  5 2010, 00:12:20)
> [GCC 4.2.1 (Apple Inc. build 5664)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> class MyContainer(object):# no special inheritance
> ...     def __len__(self):
> ...         return 42
> ...
>>>> # didn't do any registration.
>>>> from collections import Sized
>>>> issubclass(MyContainer, Sized)
> True
>>>> isinstance(MyContainer(), Sized)
> True

You're right, I forgot about subclass check. But that's really a
placebo, because it statically checks the object's *class* for such
method, not the actual instance:

from collections import Sized

class MyObj(object):
    pass

mo = MyObj()
mo.__len__ = lambda: 1


print isinstance(mo, Sized)
False

> Not precisely that I know of, no. The `abc`/`collections` system comes
> closest, but it does not check method signatures; it merely verifies
> methods' existence.

It only verifies the method's existence on the class. It does nothing
of what I'd like at runtime.


> You could *definitely* write something like that by combining the
> `abc` and `inspect` modules though:
> http://docs.python.org/library/inspect.html#inspect.getargspec
> http://docs.python.org/library/abc.html#abc.ABCMeta.__subclasshook__

Yes, I'm experimenting with inspect for signature matching.

> Duck typing partisans would question what the point of such an
> elaborate mechanism would be when it won't change the fact that your
> type errors will still occur at run-time and be of essentially the
> same character as if you didn't use such a mechanism in the first
> place.

The point is that this way I might identify ducktypes - at runtime -
in a way that doesn't clutter code. getattr() blocks are simply
boring.

Of course the runtime exception-check approach might work as well
(call the method and see whether it crashes) and I may finally pick
that approach, but I'd like not to clutter my code with explicit
try...except blocks. The very same approach might help.

 The chance for signature mismatch is of course high when using
extreme runtime dynamic proxies (methods with *args, **kwargs
signature), but at least I won't try faking static typing. Anything I
fetch would just be runtime information.

-- 
Alan Franzoni
--
contact me at public@[mysurname].eu



More information about the Python-list mailing list