PySequence_Check

Michael P. Reilly Michael.P..Reilly at p98.f112.n480.z2.fidonet.org
Wed Jun 30 16:07:14 CEST 1999


From: "Michael P. Reilly" <arcege at shore.net>

Tim Peters <tim_one at email.msn.com> wrote:
: [Reuben Sumner]
:> How can I do the equivalent of a PySequence_Check in Python?
:> GvR told me that the question was illdefined (if I explained it correctly)
:> and to ask here.  It seems that some of the functions in abstract.h
:> are available from python (len(), callable()) and others are not
:> (PySequence_Check, PyNumber_Check).
:>
:> What am I missing?

: For starters, unquestioning faith in Guido's pronouncements <wink>.

:> I have a nested structure of lists and tuple and I just want to know
:> when I have bottomed out.

: Then why not check for that directly and be done with it?

:> I can check for tuple or list indivually but that is ugly and
:> inflexible.

: Not to mention simple, obvious and unsurprising <wink>.

:> I could just try indexing and see if there was an exception but that
:> is not much better.

: OK, you tell me:  what *is* a sequence?  Answer that, and you'll know how to
: check for it <0.5 wink>.  Before answering too fast, note that mapping types
: can be indexed without raising an exception, and so can strings.  Do you
: want your nest of "lists and tuples" *not* to "bottom out" at a string?
: Probably not -- but if so, you're not really interested in testing whether
: it's a sequence!  Note too that user-defined classes can support the
: __getitem__ protocol without supporting the __getslice__ protocol, or vice
: versa.  Are either of those sequences, or do they need to support both?
: Whichever way you answer, half the world will disagree.

: I think that, in most cases, when people say "sequence":  (A) it's
: ill-defined <wink>; and, (B) after five rounds of tedious questioning they
: end up deciding they mean "responds to slicing but isn't a string".  So
: there you go:

: def issequence(x):
:     try:
:         x[0:0]
:     except:
:         return 0
:     return type(x) is not type("")

My basis (in my own programming) has been:
  import types, UserList
  def issequence(x):
    return (isinstance(x, types.ListType) or
            isinstance(x, types.TupleType) or
            isinstance(x, UserList.UserList))

It is very restrictive in some cases, but if I want a user defined
sequence, I usually _try_ to make one from UserList.

  -Arcege




More information about the Python-list mailing list