Behaviour-based interface/protocol implementation?

Alan Franzoni mailing at franzoni.eu
Thu Jan 27 17:23:56 EST 2011


On Thu, Jan 27, 2011 at 10:30 PM, Carl Banks <pavlovevidence at gmail.com> wrote:
> Write some kind of signature proxy to do it.

I don't have a specific implementation idea yet, I see how that grows.

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

Yes, but asking is better than blinding reimplementing :-)

> 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

Sure. That's an approach. But this has drawbacks.

- it violates the CQS principle:
http://en.wikipedia.org/wiki/Command-query_separation

- Maybe my interface has not just a single method, and I might want to
call multiple methods on my object. I need to check for all signatures
before proceeding.

-  When calling the method, if an exception is raised - either
AttributeError or TypeError most of the times - it could not be
generated from my own call, but from a call deeper into the stack;
It's easy to just think "that object doesn't support that interface" I
could mistake an object for not supporting an interface, and I could
silently swallow a true runtime exception instead. Maybe some stack
analysis could be performed, but I'd prefer to check as much as I can
*before* calling.

- Sometimes I'd like to group objects depending on their *behaviour*
(not their type), and then feed them somewhere else without actually
calling their methods. If I can know their behaviour just after
they've been called, it might be just too late.


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



More information about the Python-list mailing list