[Python-Dev] Re: Sets: elt in dict, lst.include

Tim Peters tim.one@home.com
Sat, 3 Feb 2001 00:42:06 -0500


[Skip Montanaro]
> The problem that rolls around in the back of my mind from time-to-time
> is that since Python doesn't currently support interfaces, checking
> for specific methods seems to be the only reasonable way to determine
> if a object does what you want or not.

Except that-- alas! --"what I want" is almost always for it to respond to
some specific methods.  For example, I don't believe I've *ever* written a
class that responds to all the "number" methods (in particular, I'm almost
certain not to bother implementing a notion of "shift").  It's also rare for
me to define a class that implements all the "sequence" or "mapping"
methods.  So if we had a Interface.Sequence, all my code would still check
for individual sequence operations anyway.  Take it to the extreme, and each
method becomes an Interface unto itself, which then get grouped into
collections in different ways by different people, and in the end I *still*
check for specific methods rather than fight with umpteen competing
hierarchies.

The most interesting "interfaces" to me are things like EuclideanDomain:  a
set of guarantees about how methods *interact*, and almost nothing to do
with which methods a thing supports.  A simpler example is TotalOrdering:
there is no method unique to total orderings, instead it's a guarantee about
how cmp *behaves*.

If you want know whether an object x supports slicing, *trying* x[:0] is as
direct as it gets.  You just hope that x isn't an instance of

class Human:
    def __getslice__(self, lo, hi):
        """Return a list of activities planned for human self.

        lo and hi bound the timespan of activities to be returned,
        in seconds from the epoch.  If lo is less than the birthdate
        of self, treat lo as if it were self's birthdate.  If hi is
        greater than the expected lifetime of self, treat hi as if
        it were the expected lifetime of self, but also send an
        execution order to ensure that self does not live beyond
        that time (this may seem drastic, but the alternative was
        complaints from customers who exceeded their expected
        lifetimes, and then demanded to know why "the stupid
        software" cut off their calendars "early" -- hey, we'll
        implement infinite memory when humans are immortal).
        """

don't-think-it-hasn't-happened<wink>-ly y'rs  - tim