python / cpython

The Python programming language
https://www.python.org
Other
62.35k stars 29.94k forks source link

Timedelta cannot be used in match statements #123882

Open u3Izx9ql7vW4 opened 1 week ago

u3Izx9ql7vW4 commented 1 week ago

Bug report

Bug description:

Timedelta cannot be evaluated in match statements, see example below

from datetime import timedelta

td = timedelta(hours=1)

print(td == timedelta(hours=1)) # evaluates to True

match td:
    case timedelta(days=1):
        print('day')
    case timedelta(hours=1):
        print('hour')
    case _:
        print('unhandled') # prints `unhandled`

CPython versions tested on:

3.11

Operating systems tested on:

macOS

terryjreedy commented 1 week ago

Please add the traceback or if none, explain 'cannot be used'. What happens that you say this?

ronaldoussoren commented 1 week ago

The arguments in a match pattern are compared to attributes of the object, that is:

match td:
    case timedelta(hours=1):
         print("hour")

is more or less equivalent to:


if isinstance(td, timedelta) and hasattr(td, "hours") and td.hours == 1:
    print("hour")

Timedelta instances do not have a "hours" attributes. Changing this would be a backward incompatibility break, especially for the attributes days and seconds (timedelta(weeks=4).days == 28).