[New-bugs-announce] [issue7942] Inconsistent error types/messages for __len__ between old and new-style classes

Paul Boddie report at bugs.python.org
Tue Feb 16 18:36:41 CET 2010


New submission from Paul Boddie <paul at boddie.org.uk>:

As noted here:

http://www.selenic.com/pipermail/mercurial/2010-February/030068.html

This is probably documented somewhere, and there may even be a good reason for the difference, but old-style classes raise TypeError when __len__ returns a non-int, whereas new-style classes raise OverflowError. The latter is probably just as valid, but the message is a bit obscure for debugging purposes.

Maybe this went away after 2.5 - if so, sorry for the noise!

Here's an illustration of the problem:

Python 2.5.4 (r254:67916, Nov  4 2009, 17:59:46)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class C:
...     def __len__(self):
...             return 2**35
...
>>> c = C()
>>> len(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __len__() should return an int
>>> class C(object):
...     def __len__(self):
...             return 2**35
...
>>> c = C()
>>> len(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to int

----------
components: Interpreter Core
messages: 99421
nosy: pboddie
severity: normal
status: open
title: Inconsistent error types/messages for __len__ between old and new-style classes
type: behavior
versions: Python 2.5

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


More information about the New-bugs-announce mailing list