Type Hierarchies

Steve Purcell stephen_purcell at yahoo.com
Wed Feb 14 12:40:02 CET 2001


Burkhard Kloss wrote:
> Is there a way to check whether an object is a sequence? I'm not interested
> in the specific type, just that it qualifies as a sequence, so it could be
> built-in or user defined sequence. The language spec talks about type
> hierarchies, but if there's any way to access that concept in code I must
> have missed it.

There's no real way to do this. As I spotted at the end of one of Tim Peters'
posts on this topic,

 "in-Python-what-you-want-to-do-with-an-object-is-more-important-than-
  what-you-call-it"


> Obviously I can try a call, and catch the exception:
> 
> def is_seq(a):
>     try:
>         len(a)
>         return 1
>     except:
>         return 0

This kind of thing is probably the best that you can hope for. The most
pythonic way (shocking though it may sound to some) is to throw the object
you hope is a sequence into the function that will use it, and test that in
ordinary use of your system the function always works correctly.

-Steve

-- 
Steve Purcell, Pythangelist
http://pyunit.sourceforge.net/
http://pyserv.sourceforge.net/
Available for consulting and training.
"Even snakes are afraid of snakes." -- Steven Wright




More information about the Python-list mailing list