[New-bugs-announce] [issue11674] list(obj), tuple(obj) swallow TypeError (in _PyObject_LengthHint)

Elvis Pranskevichus report at bugs.python.org
Fri Mar 25 21:38:10 CET 2011


New submission from Elvis Pranskevichus <elprans at gmail.com>:

Consider the following:

>>> class Test:
...     def __init__(self):
...         self.items = []
...     def __len__(self):
...         if not self.items:
...             self.items = list(self.calc_items())
...         return len(self.items)
...     def __iter__(self):
...         return iter(self.items)
...     def calc_items(self, number):
...         return range(1, number)
... 
>>> l = list(Test())
>>> print(l)
[]
>>> t = tuple(Test())
>>> print(t)
()


In the above example calc_items() method is called with a missing argument, which raises TypeError.  That TypeError is being wrongly interpreted as "object of type 'Test' has no len()" and is swallowed by _PyObject_LengthHint().  

The result is entirely unpredictable as the bug is masked, which is especially annoying for objects that can have a complex call graph under __len__().  Possible solution would be to adjust _PyObject_LengthHint() to rely on some other exception rather than straight TypeError.  Swallowing a generic exception like that is bad.

----------
components: Interpreter Core
messages: 132150
nosy: Elvis.Pranskevichus
priority: normal
severity: normal
status: open
title: list(obj), tuple(obj) swallow TypeError (in _PyObject_LengthHint)
type: behavior
versions: Python 2.5, Python 2.6, Python 2.7, Python 3.1, Python 3.2, Python 3.3

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11674>
_______________________________________


More information about the New-bugs-announce mailing list