[New-bugs-announce] [issue26983] float() can return not exact float instance

Serhiy Storchaka report at bugs.python.org
Mon May 9 09:46:33 EDT 2016

New submission from Serhiy Storchaka:

The float constructor can return an instance of float subclass.

>>> class FloatSubclass(float):
...     pass
>>> class BadFloat:
...     def __float__(self):
...         return FloatSubclass(1.2)
>>> type(float(BadFloat()))
<class '__main__.FloatSubclass'>

Comparing with other types, complex() always returns complex:

>>> class ComplexSubclass(complex):
...     pass
>>> class BadComplex:
...     def __complex__(self):
...         return ComplexSubclass(1.2, 3.4)
>>> type(complex(BadComplex()))
<class 'complex'>

And int() can return an instance of int subclass, but this behavior is deprecated:

>>> class BadInt:
...     def __int__(self):
...         return True
>>> int(BadInt())
__main__:1: DeprecationWarning: __int__ returned non-int (type bool).  The ability to return an instance of a strict subclass of int is deprecated, and may be removed in a future version of Python.

May be we should either deprecate __float__ returning non-float (as for int), or convert the result to exact float (as for complex).

The constructor of float subclass always returns an instance of correct type.

>>> class FloatSubclass2(float):
...     pass
>>> type(FloatSubclass2(BadFloat()))
<class '__main__.FloatSubclass2'>

components: Interpreter Core
messages: 265191
nosy: mark.dickinson, serhiy.storchaka
priority: normal
severity: normal
status: open
title: float() can return not exact float instance
type: behavior
versions: Python 3.6

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list