From 9b169699eecb61b620e50d4eb2160059afcba2a2 Mon Sep 17 00:00:00 2001 From: draarivpatel-ui <287273626+draarivpatel-ui@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:26:59 -0600 Subject: [PATCH] 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 --- src/pendulum/duration.py | 19 ++++++++++ tests/duration/test_behavior.py | 64 +++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) diff --git a/src/pendulum/duration.py b/src/pendulum/duration.py index d6cc0657d..aca9cd99f 100644 --- a/src/pendulum/duration.py +++ b/src/pendulum/duration.py @@ -2,6 +2,7 @@ from datetime import timedelta from typing import TYPE_CHECKING +from typing import Any from typing import cast from typing import overload @@ -16,6 +17,7 @@ if TYPE_CHECKING: from typing_extensions import Self + from typing_extensions import SupportsIndex def _divide_and_round(a: float, b: float) -> int: @@ -295,6 +297,23 @@ def as_timedelta(self) -> timedelta: """ return timedelta(seconds=self.total_seconds()) + def __reduce__( + self, + ) -> tuple[type[Self], tuple[int, int, int], dict[str, Any]]: + return self.__reduce_ex__(2) + + def __reduce_ex__( + self, protocol: SupportsIndex + ) -> tuple[type[Self], tuple[int, int, int], dict[str, Any]]: + # The reduction inherited from timedelta only keeps the normalized + # day/second/microsecond constructor arguments, which drops the + # calendar units (years and months) the duration was built with. + # The instance state is preserved alongside them so that pickling + # and copying round-trip without losing information. + _, args = timedelta.__reduce__(self) + + return self.__class__, args, dict(self.__dict__) + def __str__(self) -> str: return self.in_words() diff --git a/tests/duration/test_behavior.py b/tests/duration/test_behavior.py index cf60282fa..88ce4a322 100644 --- a/tests/duration/test_behavior.py +++ b/tests/duration/test_behavior.py @@ -2,6 +2,7 @@ import pickle +from copy import copy from copy import deepcopy from datetime import timedelta @@ -20,6 +21,69 @@ def test_pickle() -> None: assert it == it2 +@pytest.mark.parametrize( + "duration, expected", + [ + ( + pendulum.duration(years=2, months=3, weeks=1, days=2), + {"years": 2, "months": 3, "weeks": 1, "days": 2}, + ), + ( + pendulum.duration(years=-1, months=-5, weeks=-2, days=-3), + {"years": -1, "months": -5, "weeks": -2, "days": -3}, + ), + ( + pendulum.duration( + years=1, + months=-2, + weeks=1, + days=-4, + hours=5, + minutes=-6, + seconds=7, + microseconds=8, + ), + { + "years": 1, + "months": -2, + "weeks": 0, + "days": 3, + "hours": 4, + "minutes": 54, + "seconds": 7, + "microseconds": 8, + }, + ), + ( + pendulum.duration(microseconds=42), + { + "years": 0, + "months": 0, + "weeks": 0, + "days": 0, + "microseconds": 42, + }, + ), + ], +) +def test_pickle_preserves_calendar_units(duration, expected) -> None: + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + restored = pickle.loads(pickle.dumps(duration, protocol=protocol)) + + assert restored == duration + assert restored.total_seconds() == duration.total_seconds() + assert str(restored) == str(duration) + assert_duration(restored, **expected) + + +def test_copy_preserves_calendar_units() -> None: + duration = pendulum.duration(years=2, months=3, weeks=1, days=2) + copied = copy(duration) + + assert copied == duration + assert_duration(copied, years=2, months=3, weeks=1, days=2) + + def test_comparison_to_timedelta() -> None: duration = pendulum.duration(days=3)