Type Hierarchies

Prateep Siamwalla teep at inet.co.th
Wed Feb 14 08:02:46 EST 2001


Hi, after browsing through D.Beazley's Python Essential Reference (p 20), I
believe this is what you are looking for ... (apologies if I'm way off)

import types

def am_i_a_sequence(ob):
    return type(ob) in
[types.StringType,types.ListType,types.TupleType,types.XRangeType]

hope this helps,
['t','e','e','p']



Burkhard Kloss <bk at xk7.com> wrote in message
news:982149142.9745 at master.nyc.kbcfp.com...
> 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.
>
> Obviously I can try a call, and catch the exception:
>
> def is_seq(a):
>     try:
>         len(a)
>         return 1
>     except:
>         return 0
>
> which works:
>
> assert is_seq( [] )
> assert is_seq( () )
> assert is_seq( "" )
> assert not is_seq( 1 )
>
> but isn't very elegant.  It's probably also not very fast...
>
> Am I missing something obvious here? Are there better ways?
>
> Thanks,
>
>     Burkhard
>
>
>
>





More information about the Python-list mailing list