Skip to content

time.sleep() should support objects with __float__ #79888

Closed as duplicate
Closed as duplicate

Description

@jdemeyer
BPO 35707
Nosy @ronaldoussoren, @ncoghlan, @abalkin, @vstinner, @serhiy-storchaka, @jdemeyer, @MojoVampire, @pganssle, @remilapeyre
PRs
  • bpo-26669: Reject float infinity in time functions #11507
  • bpo-26669: Reject float infinity in time functions #11507
  • gh-79888: support __index__ and __float__ in time functions #11636
  • gh-79888: support __index__ and __float__ in time functions #11636
  • gh-79888: support __index__ and __float__ in time functions #11636
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = None
    created_at = <Date 2019-01-10.15:58:39.782>
    labels = ['interpreter-core', '3.10']
    title = 'time.sleep() should support objects with __float__'
    updated_at = <Date 2020-05-23.00:14:27.187>
    user = 'https://github.com/jdemeyer'

    bugs.python.org fields:

    activity = <Date 2020-05-23.00:14:27.187>
    actor = 'cheryl.sabella'
    assignee = 'none'
    closed = False
    closed_date = None
    closer = None
    components = ['Interpreter Core']
    creation = <Date 2019-01-10.15:58:39.782>
    creator = 'jdemeyer'
    dependencies = []
    files = []
    hgrepos = []
    issue_num = 35707
    keywords = ['patch', 'patch']
    message_count = 29.0
    messages = ['333391', '333395', '333396', '333397', '333401', '333404', '333416', '333547', '333550', '333554', '333555', '333961', '333963', '333968', '333969', '334120', '334121', '334122', '334125', '334128', '334129', '334131', '334136', '334480', '334486', '334509', '339123', '349004', '349560']
    nosy_count = 10.0
    nosy_names = ['ronaldoussoren', 'ncoghlan', 'belopolsky', 'vstinner', 'serhiy.storchaka', 'jdemeyer', 'josh.r', 'p-ganssle', 'remi.lapeyre', 'AVINASH MISHRA']
    pr_nums = ['11507', '11507', '11636', '11636', '11636']
    priority = 'normal'
    resolution = None
    stage = 'patch review'
    status = 'open'
    superseder = None
    type = None
    url = 'https://bugs.python.org/issue35707'
    versions = ['Python 3.10']

    Linked PRs

    Activity

    1. jdemeyer commented on Jan 18, 2019

      @jdemeyer
      ContributorAuthor

      I guess I should wait until PR 11507 is merged, to avoid merge conflicts.

    2. vstinner commented on Jan 18, 2019

      @vstinner
      Member

      No please don't wait for my PR 11507. I'm not sure that it's correct, and this bug is more important than NaN/inf :-)

    3. jdemeyer commented on Jan 21, 2019

      @jdemeyer
      ContributorAuthor

      To avoid code duplication, it's tempting to merge _PyTime_FromObject and _PyTime_ObjectToDenominator

      These two functions almost do the same, but not quite.

    4. ronaldoussoren commented on Jan 21, 2019

      @ronaldoussoren
      Contributor

      As a late response to msg333416 and msg333547, I don't agree with looking at __index__ in _PyTime_FromObject.

      The __index__ method is used when an object can be used as the index for a sequence, but should not silently convert to int or float. See <https://www.python.org/dev/peps/pep-0357/\>.

    5. jdemeyer commented on Jan 21, 2019

      @jdemeyer
      ContributorAuthor

      The motivation for PEP-357 was certainly using an object as the index for a sequence, but that's not the only use case.

      In fact PEP-357 states "For example, the slot can be used any time Python requires an integer internally"

      So despite the name __index__, I think that this is now the de facto standard for "convert the object (which is some kind of integer) to a Python int without loss of precision".

    6. ronaldoussoren commented on Jan 21, 2019

      @ronaldoussoren
      Contributor

      Using __index__ here doesn't feel right, although I can't explain why yet.

    7. jdemeyer commented on Jan 21, 2019

      @jdemeyer
      ContributorAuthor

      If __index__ doesn't "feel" right, what do you propose then to fix this issue, keeping in mind the concerns of https://bugs.python.org/issue35707#msg333401

    8. jdemeyer commented on Jan 21, 2019

      @jdemeyer
      ContributorAuthor

      In other words: if we can only use __float__ and __int__, how do we know which one to use?

    9. jdemeyer commented on Jan 21, 2019

      @jdemeyer
      ContributorAuthor

      If we want to support other numerical types with loss in double rounding

      Looking at the existing code, I can already see several double-rounding "bugs" in the code, so I wouldn't be too much concerned here...

    10. ronaldoussoren commented on Jan 21, 2019

      @ronaldoussoren
      Contributor

      In other words: if we can only use __float__ and __int__, how do we know which one to use?

      I guess __index__. I've read the definition of object.__index__ in the data model documentation, and using __index__ for this conversion is fine. I need to educate my sense for when it's right to use this method...

      Sorry about the noise.

    11. added
      interpreter-core
      on Jan 25, 2019
    12. MojoVampire commented on Jan 28, 2019

      MojoVampiremannequin
      Mannequin

      You've got a reference leak in your __index__ based paths. PyNumber_Index is returning a new reference (either to the existing obj, or a new one, if the existing obj isn't already an int). You never release this reference. Simplest fix is to make intobj top level, initialized to NULL, and Py_XDECREF it along the convert_from_int code path (you can't DECREF it in the index specific path because it needs to survive past the goto, since it's replacing obj).

      I'm also mildly concerned by how duplicative the code becomes post-patch. If it's not a major performance hit (don't think it is; not even sure the API is even used anymore), perhaps just implement _PyTime_ObjectToTime_t as a wrapper for _PyTime_ObjectToDenominator (with a denominator of 2, so rounding simplifies to just 0 == round down, 1 == round up)?

      Example:

      int
      _PyTime_ObjectToTime_t(PyObject *obj, time_t *sec, _PyTime_round_t round)
      {
          long numerator;
          if (_PyTime_ObjectToDenominator(obj, sec, &numerator, 2, round) == 0) {
             if (numerator) {
                 if (*sec == _Py_IntegralTypeMax(time_t)) {
                     error_time_t_overflow();
                     return -1;
                 }
                 ++*sec;
             }
             return 0;
          }
          return -1;
      }

      Sorry for not commenting on GitHub, but my work computer has a broken Firefox that GitHub no longer supports properly.

    13. jdemeyer commented on Jan 28, 2019

      @jdemeyer
      ContributorAuthor

      I'm also mildly concerned by how duplicative the code becomes post-patch.

      I know, that's why I added that comment on GitHub.

      perhaps just implement _PyTime_ObjectToTime_t as a wrapper for _PyTime_ObjectToDenominator

      Sure, but will that increase the chances of PR 11636 being accepted? Unless a core developer who is willing to merge that PR asks me that, I'd rather not add extra complications to that PR. (to be clear: I mean no offense, it's just that getting a CPython PR accepted is hard)

    14. jdemeyer commented on Jan 29, 2019

      @jdemeyer
      ContributorAuthor

      You've got a reference leak in your __index__ based paths.

      Thanks for pointing that out. I fixed that now.

    15. jdemeyer commented on Mar 29, 2019

      @jdemeyer
      ContributorAuthor

      Is anybody willing to review PR 11636?

    16. jdemeyer commented on Aug 4, 2019

      @jdemeyer
      ContributorAuthor

      If we want to support other numerical types with loss in double rounding, the most reliable way is to represent them as fractions (x.as_integer_ratio() or (x.numerator, x.denominator))

      See https://discuss.python.org/t/pep-3141-ratio-instead-of-numerator-denominator/2037/24?u=jdemeyer for a proposal to define __ratio__ for this.

    17. vstinner commented on Aug 13, 2019

      @vstinner
      Member

      See also bpo-20861.

    18. added
      3.10 (EOL)
      and removed
      3.7 (EOL)
      3.8 (EOL)
      on May 23, 2020
    19. transferred this issue fromon Apr 10, 2022
    20. ald-extrahop commented on Aug 3, 2023

      @ald-extrahop

      If this issue is covering all the _PyTime_FromObject() uses, the change to PyLong_AsLongLong() in Python 3.10 (#80229) increased the severity. Many time functions that accept floats by design raise TypeError when passed (e.g.) a decimal.Decimal (they previously just printed a DeprecationWarning).

    21. StanFromIreland commented on Aug 12, 2025

      @StanFromIreland
      Member

      The error message now contradicts the behavior:

      >>> class Half(object):
      ...     def __float__(self):
      ...         return 0.5
      ... import time
      ... time.sleep(Half())
      ... 
      Traceback (most recent call last):
        File "<python-input-5>", line 5, in <module>
          time.sleep(Half())
          ~~~~~~~~~~^^^^^^^^
      TypeError: 'Half' object cannot be interpreted as an integer or float
      
    22. added
      type-bug
      and removed
      3.10 (EOL)
      on Aug 12, 2025
    23. StanFromIreland commented on Dec 20, 2025

      @StanFromIreland
      Member

      This was fixed by Serhiy in 1a2e00c:

      >>> class Half(object):
      ...     def __float__(self):
      ...         return 0.5
      ... import time
      ... time.sleep(Half())
      ... 
      >>> 
      
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Assignees

    No one assigned

      Labels

      interpreter-coretype-bug

      Projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions