Force keyword-only args for Duration (prevent footgun) (#19756)

So people have to specify which time unit they want to use.

Spawning from
https://github.com/element-hq/synapse/pull/19394#discussion_r3188418426
This commit is contained in:
Eric Eastwood
2026-05-07 10:38:56 -05:00
committed by GitHub
parent 2829a146d3
commit 4911296fb5
2 changed files with 28 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
Force keyword-only args for `Duration` (prevent footgun) so people have to specify which time unit they want to us.
+27
View File
@@ -32,6 +32,33 @@ class Duration(timedelta):
```
"""
# Using `__new__` (instead of `__init__`) because that's what `timedelta` uses
def __new__(
cls,
# The whole goal of overriding `__new__` is to require keyword-only arguments.
# Without this, `Duration(5)` would create a duration represnting 5 *days*
# (timedelta's default), but callers almost certainly want to specify which unit
# like seconds or hours.
*,
days: float = 0,
seconds: float = 0,
microseconds: float = 0,
milliseconds: float = 0,
minutes: float = 0,
hours: float = 0,
weeks: float = 0,
) -> "Duration":
return super().__new__(
cls,
days=days,
seconds=seconds,
microseconds=microseconds,
milliseconds=milliseconds,
minutes=minutes,
hours=hours,
weeks=weeks,
)
def as_millis(self) -> int:
"""Returns the duration in milliseconds."""
return int(self / _ONE_MILLISECOND)