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

Guido van Rossum guido@digicool.com
Tue, 23 Jan 2001 10:31:39 -0500


> 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."

> 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?)

--Guido van Rossum (home page: http://www.python.org/~guido/)