New submission from Elvis Pranskevichus <elpr...@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 <rep...@bugs.python.org>
<http://bugs.python.org/issue11674>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to