New submission from Serhiy Storchaka <storchaka+cpyt...@gmail.com>:

Currently, C API functions that convert a Python number to a C integer like 
PyLong_AsLong() and argument parsing functions like PyArg_ParseTuple() with 
integer converting format units like 'i' use the __int__() special method for 
converting objects which are not instances of int or int subclasses. This leads 
to dropping the fractional part if the object is not integral number (e.g. 
float, Decimal or Fraction). In some cases, there is a special check for float, 
but it does not prevent truncation for Decimal, Fraction and other numeric 
types.

For example:

>>> chr(65.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: integer argument expected, got float
>>> chr(Decimal('65.5'))
'A'

The proposed PR makes all these functions using __index__() instead of 
__int__() if available and emit a deprecation warning when __int__() is used 
for implicit conversion to a C integer.

>>> chr(Decimal('65.5'))
<stdin>:1: DeprecationWarning: an integer is required (got type decimal.Decimal)
'A'

In future versions only __index__() will be used for the implicit conversion, 
and __int__() will be used only in the int constructor.

----------
components: Interpreter Core
messages: 336041
nosy: mark.dickinson, serhiy.storchaka, vstinner
priority: normal
severity: normal
status: open
title: Deprecate implicit truncating when convert Python numbers to C integers
type: enhancement
versions: Python 3.8

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

Reply via email to