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

Tim Peters tim.one@home.com
Tue, 23 Jan 2001 00:03:18 -0500

> ...
> At the moment, to see if something is a sequence i believe i have to
> say something like
>     try:
>         x[0]
>     except:
>         # not a sequence
>     else:
>         # okay, it's a sequence
> or
>     if hasattr(x, '__getitem__') or type(x) in [type(()), type([])]:
>         ...
> Is there, or should there be, a better way to do this?

Dunno.  What's a sequence?  If you want to know whether x[0] will blow up,
trying x[0] is the most obvious way.  BTW, I expect trying x[:0] is a better
idea:  doesn't succeed for dicts, and doesn't blow up for an irrelevant
reason if x is an empty sequence.  BTW2, your second method suggests an
uncomfortable truth:  many contexts that want "a sequence" don't want
strings to pass the test, despite that strings are as much sequences as
lists in Python, no matter how "a sequence" is defined.

afraid that-what-you-want-to-do-with-it-is-more-important-than-what-
    python-calls-it-ly y'rs  - tim