Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion schema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -905,7 +905,15 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:
f'"{self._schema!r}" is too complex.'
)
self.default = default
self.key = str(self._schema)
# Preserve the original key object so the default fills the output
# under the same key (and key type) that a present key would use.
# Stringifying here made an absent optional produce ``str(key)``
# (e.g. ``"5"``) while a present key kept its real type (``5``).
self.key = (
self._schema.schema
if isinstance(self._schema, Literal)
else self._schema
)

def __hash__(self) -> int:
return hash(self._schema)
Expand Down
11 changes: 11 additions & 0 deletions test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,17 @@ def test_dict_optional_defaults():
Optional(And(str, Use(int)), default=7)


def test_dict_optional_default_preserves_key_type():
# A non-string key must keep its type when the default fills it in, just
# as it does when the key is present in the data.
for key in (5, None, 1.5):
schema = Schema({Optional(key, default="x"): str})
assert schema.validate({}) == {key: "x"}
# present and absent must agree on the output key type
present = {key: "p"}
assert schema.validate(present) == present


def test_dict_subtypes():
d = defaultdict(int, key=1)
v = Schema({"key": 1}).validate(d)
Expand Down