How do I test if an object is a sequence?

John Roth newsgroups at jhrothjr.com
Mon Dec 22 16:18:10 EST 2003


"Aahz" <aahz at pythoncraft.com> wrote in message
news:bs79nr$k7j$1 at panix1.panix.com...
> In article <vuea4oagaq1rd6 at news.supernews.com>,
> John Roth <newsgroups at jhrothjr.com> wrote:
> >"Max M" <maxm at mxm.dk> wrote in message
> >news:3fe6fbb1$0$69983$edfadb0f at dread12.news.tele.dk...
> >>
> >> Is there a common idiom for testing if an object is a sequence?
> >>
> >> Both list, tuple and non-standard objects etc. I have Googled, but
> >> didn't find a usable answer.
> >
> >The best way I know of is to check for the existance of either __iter__
> >or __getitem__. This gets you roughly the same results as either the
> >for statement or the iter() built-in function.
>
> Not quite.  Try using ``for`` on a dict in Python 2.1 or earlier.

Well, yes, but dicts aren't the only problem. The notion of 'sequence'
is sufficiently ill-defined that you almost need to know what the
OP wants to do with it to give a usable answer. For example, do you
want to accept infinite sequences? Some generators will do that to you,
on the other hand, testing for __len__ isn't going to let you accept
files, which are neither infinite nor do they have a usable __len__ or
__getitem__.

And, as you point out, everything that has a __getitem__ and
a __len__ won't accept numeric subscripts. Like dicts.

John Roth


> -- 
> Aahz (aahz at pythoncraft.com)           <*>
http://www.pythoncraft.com/
>
> Weinberg's Second Law: If builders built buildings the way programmers
wrote
> programs, then the first woodpecker that came along would destroy
civilization.






More information about the Python-list mailing list