Skip to content

Commit

Permalink
Fix pickle/copy support for the missing singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
mattclay authored and davidism committed Dec 19, 2024
1 parent ba8847a commit 7232b82
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Unreleased
call. :issue:`2021`
- Fix dunder protocol (`copy`/`pickle`/etc) interaction with ``Undefined``
objects. :issue:`2025`
- Fix `copy`/`pickle` support for the internal ``missing`` object.
:issue:`2027`


Version 3.1.4
Expand Down
13 changes: 11 additions & 2 deletions src/jinja2/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,17 @@

F = t.TypeVar("F", bound=t.Callable[..., t.Any])

# special singleton representing missing values for the runtime
missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})()

class _MissingType:
def __repr__(self) -> str:
return "missing"

def __reduce__(self) -> str:
return "missing"


missing: t.Any = _MissingType()
"""Special singleton representing missing values for the runtime."""

internal_code: t.MutableSet[CodeType] = set()

Expand Down
12 changes: 12 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import copy
import pickle
import random
from collections import deque
Expand Down Expand Up @@ -183,3 +184,14 @@ def test_consume():
consume(x)
with pytest.raises(StopIteration):
next(x)


@pytest.mark.parametrize("protocol", range(pickle.HIGHEST_PROTOCOL + 1))
def test_pickle_missing(protocol: int) -> None:
"""Test that missing can be pickled while remaining a singleton."""
assert pickle.loads(pickle.dumps(missing, protocol)) is missing


def test_copy_missing() -> None:
"""Test that missing can be copied while remaining a singleton."""
assert copy.copy(missing) is missing

0 comments on commit 7232b82

Please sign in to comment.