Skip to content

Commit 7cc7f6b

Browse files
authored
Define trio.Event.__bool__() to reduce bugs (#3322)
2 parents 8dd7d8e + 02c3794 commit 7cc7f6b

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

newsfragments/3322.deprecated.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Implement ``bool(trio.Event)`` and have it raise a `DeprecationWarning` and tell users to use `trio.Event.is_set` instead. This is an alternative to ``mypy --enable-error-code=truthy-bool`` for users who don't use type checking.

src/trio/_sync.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
import math
4-
from typing import TYPE_CHECKING, Protocol
4+
from typing import TYPE_CHECKING, Literal, Protocol, TypeVar
55

66
import attrs
77

@@ -16,13 +16,31 @@
1616
enable_ki_protection,
1717
remove_parking_lot_breaker,
1818
)
19+
from ._deprecate import warn_deprecated
1920
from ._util import final
2021

2122
if TYPE_CHECKING:
23+
from collections.abc import Callable
2224
from types import TracebackType
2325

26+
from typing_extensions import deprecated
27+
2428
from ._core import Task
2529
from ._core._parking_lot import ParkingLotStatistics
30+
else:
31+
T = TypeVar("T")
32+
33+
def deprecated(
34+
message: str,
35+
/,
36+
*,
37+
category: type[Warning] | None = DeprecationWarning,
38+
stacklevel: int = 1,
39+
) -> Callable[[T], T]:
40+
def wrapper(f: T) -> T:
41+
return f
42+
43+
return wrapper
2644

2745

2846
@attrs.frozen
@@ -112,6 +130,20 @@ def statistics(self) -> EventStatistics:
112130
"""
113131
return EventStatistics(tasks_waiting=len(self._tasks))
114132

133+
@deprecated(
134+
"trio.Event.__bool__ is deprecated since Trio 0.31.0; use trio.Event.is_set instead (https://github.com/python-trio/trio/issues/3238)",
135+
stacklevel=2,
136+
)
137+
def __bool__(self) -> Literal[True]:
138+
"""Return True and raise warning."""
139+
warn_deprecated(
140+
self.__bool__,
141+
"0.31.0",
142+
issue=3238,
143+
instead=self.is_set,
144+
)
145+
return True
146+
115147

116148
class _HasAcquireRelease(Protocol):
117149
"""Only classes with acquire() and release() can use the mixin's implementations."""

src/trio/_tests/test_sync.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ async def test_Event() -> None:
2323
assert not e.is_set()
2424
assert e.statistics().tasks_waiting == 0
2525

26+
with pytest.warns(
27+
DeprecationWarning,
28+
match=r"trio\.Event\.__bool__ is deprecated since Trio 0\.31\.0; use trio\.Event\.is_set instead \(https://github.com/python-trio/trio/issues/3238\)",
29+
):
30+
e.__bool__()
31+
2632
e.set()
2733
assert e.is_set()
2834
with assert_checkpoints():

0 commit comments

Comments
 (0)