[Python-Dev] Interfaces (Is X a (sequence|mapping)?)

M.-A. Lemburg mal@lemburg.com
Wed, 24 Jan 2001 15:01:33 +0100


Guido van Rossum wrote:
> 
> > Polymorphic code will usually get you more out of an
> > algorithm, than type-safe or interface-safe code.
> 
> Right.
> 
> But there are times when people want to write methods that take
> e.g. either a sequence or a mapping, and need to distinguish between
> the two.  That's not easy in Python!  Java and C++ support it very
> well though, and thus we'll always keep seeing this kind of
> complaint.  Not sure what to do, except to recommend "find out which
> methods you expect in one case but not in the other (e.g. keys()) and
> do a hasattr() test for that."

Perhaps we should provide simple means for testing a set of
available methods and slots ?!

E.g. hasinterface(obj, ('keys', 'items', '__len__'))

Objects could provide an __interface__ special attribute for this
purpose (since not all slots can be auto-detected and -verified
without side-effects).

> > BTW, there are Python interfaces to PySequence_Check() and
> > PyMapping_Check() burried in the builtin operator module in case
> > you really do care ;) ...
> >
> >       operator.isSequenceType()
> >       operator.isMappingType()
> >       + some other C style _Check() APIs
> >
> > These only look at the type slots though, so Python instances
> > will appear to support everything but when used fail with
> > an exception if they don't provide the proper __xxx__ hooks.
> 
> Yes, these should probably be deprecated.  I certainly have never used
> them!  (The operator module doesn't seem to get much use in
> general...  Was it a bad idea?)

Some of these are nice to have and provide some good performance
boost (e.g. the numeric slot access APIs). The type slot checking 
APIs are not too useful though.

-- 
Marc-Andre Lemburg
______________________________________________________________________
Company:                                        http://www.egenix.com/
Consulting:                                    http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/