Mark Dickinson added the comment:

See the related python-dev discussion started by Mark Shannon here:

http://mail.python.org/pipermail/python-dev/2013-March/125022.html

and continuing well into April here:

http://mail.python.org/pipermail/python-dev/2013-April/125042.html

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

----------
assignee: docs@python -> mark.dickinson
components: +Interpreter Core -Documentation
keywords: +patch
nosy: +ncoghlan
Added file: http://bugs.python.org/file31147/issue17576.patch

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue17576>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to