Issue 1522016: filter() doesn't use len of str/unicode/tuple subclasses (original) (raw)

Consider the following code:

class badstr(str): ... def len(self): ... return 6 ... def getitem(self, index): ... return "a" ... filter(None, badstr("bbb")) 'aaa'

I would have expected the answer to be 'aaaaaa'.

The cause for this is that Python/bltinmodule.c:filter{string,unicode,tuple} all call PyString_Size (or the appropriate equivalent), even if the sequence is a subclass of one of these types. This bypasses any overloading of len done by the subclass, as demonstrated above.

If filter() is going to respect the subclass's getitem overload, it should also respect overloading of len. The attached patch corrects this.