Skip to content

Commit af9c510

Browse files
bysiberhynek
andauthored
Fix validators.disabled() to save/restore state on nesting (#1513)
* Fix validators.disabled() to save/restore previous state on nesting * Add news fragment * Add test * Add versionchanged tag --------- Co-authored-by: Hynek Schlawack <hs@ox.cx>
1 parent ab7f8b2 commit af9c510

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

changelog.d/1513.change.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The `attrs.validators.disabled()` contextmanager can now be nested.

src/attr/validators.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,14 @@ def disabled():
7979
This context manager is not thread-safe!
8080
8181
.. versionadded:: 21.3.0
82+
.. versionchanged:: 26.1.0 The contextmanager is nestable.
8283
"""
84+
prev = get_run_validators()
8385
set_run_validators(False)
8486
try:
8587
yield
8688
finally:
87-
set_run_validators(True)
89+
set_run_validators(prev)
8890

8991

9092
@attrs(repr=False, slots=True, unsafe_hash=True)

tests/test_validators.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,22 @@ def test_disabled_ctx_with_errors(self):
9797

9898
assert _config._run_validators is True
9999

100+
def test_disabled_ctx_nested(self):
101+
"""
102+
Nested contextmanagers restore correct state.
103+
"""
104+
assert _config._run_validators is True
105+
106+
with validator_module.disabled():
107+
assert _config._run_validators is False
108+
109+
with validator_module.disabled():
110+
assert _config._run_validators is False
111+
112+
assert _config._run_validators is False
113+
114+
assert _config._run_validators is True
115+
100116

101117
class TestInstanceOf:
102118
"""

0 commit comments

Comments
 (0)