Behaviour-based interface/protocol implementation?

Carl Banks pavlovevidence at gmail.com
Thu Jan 27 16:30:26 EST 2011


On Jan 24, 2:13 am, Alan Franzoni <mail... at franzoni.eu> wrote:
> Hello,
> I'd like to have a system which lets me do certain actions if the
> duck-type of a certain objects matches what I expect, i.e. I'd like to
> have a formalization of what it's sometimes done through getattr()
> calls:
>
> if getattr(myobj, "somemethod", None) is not None:
>     myobj.somemethod(somevalue)
>
> The above approach is sometimes too naive, because a) clutters code
> with many getattr calls and ifs b) I might want to check for multiple
> attributes and c) only checks for the method name and not for the
> method's signature.

Write some kind of signature proxy to do it.

class SomeSignature(object):
    def __init__(self,target):
        self.target = target
    def somemethod(self,value):
        if hasattr(self.target,"somemethod"):
            self.target.somemethod(value)

SomeSignature(myobj).somemethod(somevalue)

Generalizing the proxy to easily accommodate all kinds of signatures
to your heart's delight left as an exercise (and it's likley to
involve metaclass programming).

> After looking at PyProtocols, zope.interface and python's own abc
> module, I'm left with a doubt: does any behaviour-based "interface
> testing" system exist for Python?

Based on this thread, you have quite specific requirements, so it's
doubtful someone else has implemented exactly what you want.


And because it hasn't been mentioned in this thread yet--surprisingly--
many people in Python prefer the EAFP strategy, "Easier to Ask
Forgiveness than Permission", that is, to just do it and handle the
resulting exception:

try:
    myobj.somemethod(somevalue)
except AttributeError:
    # doesn't fit signature, so do nothing
    pass

Personally, I have my doubts about the method in general.  It's
definitely preferrable in many cases (like opening a file, where it
avoids a race condition) but for something like this I don't see it
working out too well.  But I'm just throwing it out there.


Carl Banks



More information about the Python-list mailing list