Message396847
FWIW, there's some history here: there's a good reason that fractions.Fraction didn't originally implement __int__.
Back in the Bad Old Days, many Python functions that expected an integer would accept anything whose type implemented __int__ instead, and call __int__ to get the required integer. For example:
Python 3.7.10 (default, Jun 1 2021, 23:43:35)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import Decimal
>>> chr(Decimal("45.67"))
'-'
Effectively, __int__ was being used to mean two different things: (1) this value can be used as an integer, and (2) this value can be truncated to an integer. The solution was to introduce two new dedicated magic methods __index__ and __trunc__ for these two different meanings. See PEP 357 and PEP 3141 for some of the details. So adding __int__ to fractions.Fraction would have made things like `chr(Fraction("5/2"))` possible, too.
The behaviour above is still present (with a deprecation warning) in Python 3.9, and `chr(Decimal("45.67"))` has only finally been made a TypeError in Python 3.10.
We may now finally be in a state where ill-advised uses of __int__ in internal functions have all been deprecated and removed, so that it's safe to re-add __int__ methods.
But still, this seems mostly like an issue with the typing library. What is typing.SupportsInt intended to indicate? That an object can be used _as_ an integer, or that an object can be _truncated_ to an integer? |
|
Date |
User |
Action |
Args |
2021-07-02 07:25:46 | mark.dickinson | set | recipients:
+ mark.dickinson, mamrhein, josh.r |
2021-07-02 07:25:46 | mark.dickinson | set | messageid: <1625210746.1.0.536771008477.issue44547@roundup.psfhosted.org> |
2021-07-02 07:25:46 | mark.dickinson | link | issue44547 messages |
2021-07-02 07:25:45 | mark.dickinson | create | |
|