Elvis Pranskevichus <elpr...@gmail.com> added the comment:

The problem is that the call to __len__ is implicit.  The Exception is simply 
swallowed by a list/tuple constructor.

The main issue is that the original error is masked which makes it very hard to 
pinpoint the actual cause of the failure.  

Here's an example of how it would fail if Test had a rather naive 
implementation of __getitem__():

>>> 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)
...     def __getitem__(self, m):
...         return list(self)[m]
... 
>>> t = Test()
>>> print(t[0])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 13, in __getitem__
IndexError: list index out of range


It's not obvious in a trivial synthetic example like that, but in a complex 
case like ORM abstraction this can cause a lot of pain.

Again, I'm not talking about the __len__ and TypeError protocol, it's the 
implicit exception swallowing by what is essentially an optional optimization 
hint.  Calling len(Test()) directly would bring up the correct trace just fine.

----------

_______________________________________
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