[New-bugs-announce] [issue43929] Raise on threading.Event.__bool__ due to ambiguous nature

Aritn Sarraf report at bugs.python.org
Sat Apr 24 06:39:43 EDT 2021


New submission from Aritn Sarraf <sarraf.artin at gmail.com>:

I'll sometimes find myself accidentally doing something like this (especially after a long break from using the threading module): 
```
stop_thread = threading.Event()
...
while not stop_thread:  # bug - bool(stop_thread) will always evaluate to True
    ...
```

Since the intention behind bool(event) is ambiguous and most likely often used improperly, I think that it would be a good idea to protect against this easy to produce bug, by overriding __bool__ to raise. There is precedent for this behavior in the popular numpy library, see here:
https://github.com/numpy/numpy/blob/623bc1fae1d47df24e7f1e29321d0c0ba2771ce0/numpy/core/src/multiarray/number.c#L829

Expanding on my thoughts:
1) Most operations on a threading.Event are associated with checking the truthiness of the underlying state of the Event. Meaning that there are many opportunities for bool(event) to be called improperly.
2) I can't think of any cases where  you would want to evaluate truthiness on anything other than the underlying "set" state of the Event. The one exception I can think of being the following (however, I believe this is generally accepted to be an anti-pattern, which I don't think should be considered a redeeming case for allowing bool(event)):
```
def my_func(event=None):
    event = event or threading.Event()
    ...
```
3) It is an easy addition to protect against this. Simply by raising in __bool__
4) The only backwards incompatibilities this could create are in cases where the event is being evaluated for truthiness incorrectly, and in the anti-pattern case described in point 2.

----------
components: Library (Lib)
messages: 391771
nosy: asarraf
priority: normal
severity: normal
status: open
title: Raise on threading.Event.__bool__ due to ambiguous nature
type: behavior
versions: Python 3.10, Python 3.11, Python 3.6, Python 3.7, Python 3.8, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43929>
_______________________________________


More information about the New-bugs-announce mailing list