operator module isSequenceType with builtin set produces False

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Dec 18 23:24:07 EST 2007


En Tue, 18 Dec 2007 09:15:12 -0300, English, Mark <Mark.English at rbccm.com>  
escribió:

>>>> try: set
>>>> except NameError: from sets import Set as set
>>>> class myset_fails(set): pass
>>>> class myset_works(set):
>>>>     def __getitem__(self): pass
>>>> s = set()
>>>> fails = myset_fails()
>>>> works = myset_works()
>>>> import operator
>>>> operator.isSequenceType(s) #Not what I expected
> False
>>>> operator.isSequenceType(fails) #Not what I expected either
> False
>>>> operator.isSequenceType(works) #A hint at what isSequenceType does ?
> True
>
> Are sets not sequences ? I didn't think the isSequenceDisclaimer gave
> false negatives.

No, sets aren't sequences, as they have no order. Same as dicts, which  
aren't sequences either.
If you add a __getitem__ method, isSequenceType can only *guess* that it  
*could* be used with integer indexes, so this object *could* be (or behave  
like) a sequence. The object could be a mapping too, and there is no way  
to tell the difference without inspecting or executing __getitem__. That's  
all isSequenceType can do for arbitrary objects.

> See Raymond Hettinger's post here too:
> http://groups.google.co.uk/group/comp.lang.python/tree/browse_frm/thread
> /bd04db20cc1f23bb/36f1f48bb7be1e4b?hl=en&rnum=1&q=set+isSequenceType&_do
> ne=%2Fgroup%2Fcomp.lang.python%2Fbrowse_frm%2Fthread%2Fbd04db20cc1f23bb%
> 2F0454f5debc01c20d%3Fhl%3Den%26lnk%3Dgst%26q%3Dset%2BisSequenceType%26#d
> oc_0454f5debc01c20d
>
> Although there are suggestions that it means simply that you're headed
> in the wrong direction design wise:
> http://www.mail-archive.com/python-dev@python.org/msg11576.html
>
> but then why have isSequenceType at all ?

There are *true* sequences that it can detect, like lists, strings and all  
their subclases. For classic classes (that couldn't inherit from builtin  
types) all it can do is to guess based on __getitem__. For new style  
classes, it checks whether the slot used for __getitem__ is filled.

> Not particularly vital. Just implementing __str__ on some class and if
> one of the members was a sequence
> I was going to format that bit of data in brackets.

As R. Hettinger said, you may add your own knowledge to what  
isSequenceType says, to determine whay *you* consider a sequence in this  
context.

-- 
Gabriel Genellina




More information about the Python-list mailing list