Skip to content
Myr

Fix `copy`, `deepcopy` and `pickle` of `Sentinel` members (#3805)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents 3cbcf9b, f58ca3e · Browse files · 3 files+60 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+60 added−0 removed

  • tests:+45 added−0 removed
  • other:+15 added−0 removed

3 files+60 added−0 removed

modified:src/click/_utils.py+9 added
16 unmodified lines
1718 def __repr__(self) -> str:19 return f"{self.__class__.__name__}.{self.name}"2021 def __copy__(self) -> Sentinel:22 return self2324 def __deepcopy__(self, memo: dict[int, t.Any]) -> Sentinel:25 return self2627 def __reduce_ex__(self, protocol: object) -> tuple[t.Any, ...]:28 return getattr, (self.__class__, self.name)293031UNSET: t.Literal[Sentinel.UNSET] = Sentinel.UNSET32"""Sentinel used to indicate that a value is not set."""3334FLAG_NEEDS_VALUE: t.Literal[Sentinel.FLAG_NEEDS_VALUE] = Sentinel.FLAG_NEEDS_VALUE
11 unmodified lines
modified:tests/test_utils/test_sentinel.py+45 added
1import copy2import pickle3from decimal import Decimal4from fractions import Fraction56import pytest78import click9from click._utils import Sentinel10from click._utils import UNSET111213def test_unset_sentinel():
41 unmodified lines
55 assert value != real_value56 assert value is not real_value5758 assert value not in real_values596061@pytest.mark.parametrize("sentinel", tuple(Sentinel))62@pytest.mark.parametrize(63 "duplicate",64 (65 copy.copy,66 copy.deepcopy,67 lambda value: pickle.loads(pickle.dumps(value)),68 ),69 ids=("copy", "deepcopy", "pickle"),70)71def test_sentinel_duplication_preserves_identity(sentinel, duplicate):72 """Sentinels are singletons: copying or pickling one returns the member.7374 The default ``Enum`` reduction is ``(cls, (member.value,))``, which cannot75 round-trip a bare ``object()`` value: the copy or the unpickled value is a76 new object and ``Sentinel()`` rejects it.77 """78 assert duplicate(sentinel) is sentinel798081@pytest.mark.parametrize(82 "duplicate",83 (84 copy.copy,85 copy.deepcopy,86 lambda value: pickle.loads(pickle.dumps(value)),87 ),88 ids=("copy", "deepcopy", "pickle"),89)90def test_parameter_duplication(duplicate):91 """Every ``Parameter`` holds ``UNSET`` in ``default`` unless one is given."""92 option = click.Option(["--name"])93 assert option.default is UNSET9495 duplicated = duplicate(option)96 assert duplicated.default is UNSET97 assert duplicated.name == "name"
modified:CHANGES.md+6 added
1## Version 8.5.123Unreleased45- Fix `copy.deepcopy()` and `pickle` on a `Parameter`, `Option` or `Command`. {pr}`3805`67## Version 8.5.089Released 2026-08-2410
1654 unmodified lines