Skip to content
Merged
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
1 change: 1 addition & 0 deletions changelog.d/1448.change.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`attrs.validators.deep_mapping()` now allows to leave out either *key_validator* xor *value_validator*.
37 changes: 29 additions & 8 deletions src/attr/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,9 +378,9 @@ def deep_iterable(member_validator, iterable_validator=None):

@attrs(repr=False, slots=True, unsafe_hash=True)
class _DeepMapping:
key_validator = attrib(validator=is_callable())
value_validator = attrib(validator=is_callable())
mapping_validator = attrib(default=None, validator=optional(is_callable()))
key_validator = attrib(validator=optional(is_callable()))
value_validator = attrib(validator=optional(is_callable()))
mapping_validator = attrib(validator=optional(is_callable()))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This default made not sense given that _DeepMapping is private and only to be constructed by ourselves.


def __call__(self, inst, attr, value):
"""
Expand All @@ -390,30 +390,51 @@ def __call__(self, inst, attr, value):
self.mapping_validator(inst, attr, value)

for key in value:
self.key_validator(inst, attr, key)
self.value_validator(inst, attr, value[key])
if self.key_validator is not None:
self.key_validator(inst, attr, key)
if self.value_validator is not None:
self.value_validator(inst, attr, value[key])

def __repr__(self):
return f"<deep_mapping validator for objects mapping {self.key_validator!r} to {self.value_validator!r}>"


def deep_mapping(key_validator, value_validator, mapping_validator=None):
def deep_mapping(
key_validator=None, value_validator=None, mapping_validator=None
):
"""
A validator that performs deep validation of a dictionary.

All validators are optional, but at least one of *key_validator* or
*value_validator* must be provided.

Args:
key_validator: Validator to apply to dictionary keys.

value_validator: Validator to apply to dictionary values.

mapping_validator:
Validator to apply to top-level mapping attribute (optional).
Validator to apply to top-level mapping attribute.

.. versionadded:: 19.1.0

.. versionchanged:: 25.4.0
*key_validator* and *value_validator* are now optional, but at least one
of them must be provided.

Raises:
TypeError: if any sub-validators fail
TypeError: If any sub-validator fails on validation.

ValueError:
If neither *key_validator* nor *value_validator* is provided on
instantiation.
"""
if key_validator is None and value_validator is None:
msg = (
"At least one of key_validator or value_validator must be provided"
)
raise ValueError(msg)

return _DeepMapping(key_validator, value_validator, mapping_validator)


Expand Down
9 changes: 8 additions & 1 deletion src/attr/validators.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,16 @@ def deep_iterable(
member_validator: _ValidatorArgType[_T],
iterable_validator: _ValidatorType[_I] | None = ...,
) -> _ValidatorType[_I]: ...
@overload
def deep_mapping(
key_validator: _ValidatorType[_K],
value_validator: _ValidatorType[_V],
value_validator: _ValidatorType[_V] | None = ...,
mapping_validator: _ValidatorType[_M] | None = ...,
) -> _ValidatorType[_M]: ...
@overload
def deep_mapping(
key_validator: _ValidatorType[_K] | None = ...,
value_validator: _ValidatorType[_V] = ...,
mapping_validator: _ValidatorType[_M] | None = ...,
) -> _ValidatorType[_M]: ...
def is_callable() -> _ValidatorType[_T]: ...
Expand Down
34 changes: 34 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,8 @@ def test_success(self):
(instance_of(str), instance_of(int), 42),
(42, 42, None),
(42, 42, 42),
(42, None, None),
(None, 42, None),
],
)
def test_noncallable_validators(
Expand Down Expand Up @@ -719,8 +721,40 @@ def test_repr(self):
"<deep_mapping validator for objects mapping "
f"{key_repr} to {value_repr}>"
)

assert expected_repr == repr(v)

def test_error_neither_validator_provided(self):
"""
Raise ValueError if neither key_validator nor value_validator is
provided.
"""
with pytest.raises(ValueError) as e:
deep_mapping()

assert (
"At least one of key_validator or value_validator must be provided"
== e.value.args[0]
)

def test_key_validator_can_be_none(self):
"""
The key validator can be None.
"""
v = deep_mapping(value_validator=instance_of(int))
a = simple_attr("test")

v(None, a, {"a": 6, "b": 7})

def test_value_validator_can_be_none(self):
"""
The value validator can be None.
"""
v = deep_mapping(key_validator=instance_of(str))
a = simple_attr("test")

v(None, a, {"a": 6, "b": 7})


class TestIsCallable:
"""
Expand Down
10 changes: 10 additions & 0 deletions tests/typing_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,16 @@ class Validated:
attr.validators.instance_of(C), attr.validators.instance_of(D)
),
)
d2 = attr.ib(
type=Dict[C, D],
validator=attr.validators.deep_mapping(attr.validators.instance_of(C)),
)
d3 = attr.ib(
type=Dict[C, D],
validator=attr.validators.deep_mapping(
value_validator=attr.validators.instance_of(C)
),
)
e: str = attr.ib(validator=attr.validators.matches_re(re.compile(r"foo")))
f: str = attr.ib(
validator=attr.validators.matches_re(r"foo", flags=42, func=re.search)
Expand Down