Skip to content

Commit 9b16969

Browse files
Preserve calendar units when pickling and copying Duration
The reduction inherited from timedelta only keeps the normalized day/second/microsecond constructor arguments, so pickling or shallow copying a Duration lost the years and months it was built with even though its approximate total length survived. The instance state is now preserved alongside the constructor arguments so both round-trip without losing information. Fixes #1023
1 parent e06dace commit 9b16969

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

‎src/pendulum/duration.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from datetime import timedelta
44
from typing import TYPE_CHECKING
5+
from typing import Any
56
from typing import cast
67
from typing import overload
78

@@ -16,6 +17,7 @@
1617

1718
if TYPE_CHECKING:
1819
from typing_extensions import Self
20+
from typing_extensions import SupportsIndex
1921

2022

2123
def _divide_and_round(a: float, b: float) -> int:
@@ -295,6 +297,23 @@ def as_timedelta(self) -> timedelta:
295297
"""
296298
return timedelta(seconds=self.total_seconds())
297299

300+
def __reduce__(
301+
self,
302+
) -> tuple[type[Self], tuple[int, int, int], dict[str, Any]]:
303+
return self.__reduce_ex__(2)
304+
305+
def __reduce_ex__(
306+
self, protocol: SupportsIndex
307+
) -> tuple[type[Self], tuple[int, int, int], dict[str, Any]]:
308+
# The reduction inherited from timedelta only keeps the normalized
309+
# day/second/microsecond constructor arguments, which drops the
310+
# calendar units (years and months) the duration was built with.
311+
# The instance state is preserved alongside them so that pickling
312+
# and copying round-trip without losing information.
313+
_, args = timedelta.__reduce__(self)
314+
315+
return self.__class__, args, dict(self.__dict__)
316+
298317
def __str__(self) -> str:
299318
return self.in_words()
300319

‎tests/duration/test_behavior.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import pickle
44

5+
from copy import copy
56
from copy import deepcopy
67
from datetime import timedelta
78

@@ -20,6 +21,69 @@ def test_pickle() -> None:
2021
assert it == it2
2122

2223

24+
@pytest.mark.parametrize(
25+
"duration, expected",
26+
[
27+
(
28+
pendulum.duration(years=2, months=3, weeks=1, days=2),
29+
{"years": 2, "months": 3, "weeks": 1, "days": 2},
30+
),
31+
(
32+
pendulum.duration(years=-1, months=-5, weeks=-2, days=-3),
33+
{"years": -1, "months": -5, "weeks": -2, "days": -3},
34+
),
35+
(
36+
pendulum.duration(
37+
years=1,
38+
months=-2,
39+
weeks=1,
40+
days=-4,
41+
hours=5,
42+
minutes=-6,
43+
seconds=7,
44+
microseconds=8,
45+
),
46+
{
47+
"years": 1,
48+
"months": -2,
49+
"weeks": 0,
50+
"days": 3,
51+
"hours": 4,
52+
"minutes": 54,
53+
"seconds": 7,
54+
"microseconds": 8,
55+
},
56+
),
57+
(
58+
pendulum.duration(microseconds=42),
59+
{
60+
"years": 0,
61+
"months": 0,
62+
"weeks": 0,
63+
"days": 0,
64+
"microseconds": 42,
65+
},
66+
),
67+
],
68+
)
69+
def test_pickle_preserves_calendar_units(duration, expected) -> None:
70+
for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
71+
restored = pickle.loads(pickle.dumps(duration, protocol=protocol))
72+
73+
assert restored == duration
74+
assert restored.total_seconds() == duration.total_seconds()
75+
assert str(restored) == str(duration)
76+
assert_duration(restored, **expected)
77+
78+
79+
def test_copy_preserves_calendar_units() -> None:
80+
duration = pendulum.duration(years=2, months=3, weeks=1, days=2)
81+
copied = copy(duration)
82+
83+
assert copied == duration
84+
assert_duration(copied, years=2, months=3, weeks=1, days=2)
85+
86+
2387
def test_comparison_to_timedelta() -> None:
2488
duration = pendulum.duration(days=3)
2589

0 commit comments

Comments
 (0)