Author mark.dickinson
Recipients alex, barry, docs@python, eric.snow, ethan.furman, mark.dickinson, ncoghlan, serhiy.storchaka, vstinner
Date 2013-08-04.08:56:14
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
See the related python-dev discussion started by Mark Shannon here:

and continuing well into April here:

The consensus that emerged from that thread seems to be that calls to operator.index and to int() should always return something of exact type int.

The attached patch:

- Raises TypeError for implicit calls to nb_int that fail to return something of exact type int.  (Results of direct calls to __int__ are not checked.)

- Ensures that *all* conversions from a non-int to an int via nb_int make use of the nb_int slot, even for int subclasses.  Prior to this patch, some of the PyLong_As... functions would bypass __int__ for int subclasses.

- Adds a new private _PyLong_FromNbInt function to Objects/longobject.c, so that we have a single place for performing these conversions and making type checks, and refactors existing uses of the nb_int slot to go via this function.

- Makes corresponding changes for nb_index, which should address the original bug report.

I guess this may be too dangerous a change for Python 3.4.  In that case, I propose raising warnings instead of TypeErrors for Python 3.4 and turning those into TypeErrors in Python 3.5.

One other question:  should direct calls to __int__ and __index__ also have their return values type-checked?  That doesn't seem to happen at the moment for other magic methods (see below), so it would seem consistent to only do the type checking for interpreter-generated implicit calls to __int__ and __index__.  Nick: any opinion?

>>> class A:
...     def __len__(self): return "a string"
...     def __bool__(self): return "another string"
>>> a = A()
>>> a.__len__()
'a string'
>>> a.__bool__()
'another string'
>>> len(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> bool(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __bool__ should return bool, returned str
Date User Action Args
2013-08-04 08:56:17mark.dickinsonsetrecipients: + mark.dickinson, barry, ncoghlan, vstinner, alex, docs@python, ethan.furman, eric.snow, serhiy.storchaka
2013-08-04 08:56:17mark.dickinsonsetmessageid: <>
2013-08-04 08:56:17mark.dickinsonlinkissue17576 messages
2013-08-04 08:56:16mark.dickinsoncreate