trio icon indicating copy to clipboard operation
trio copied to clipboard

Define `trio.Event.__bool__()` to reduce bugs

Open Zac-HD opened this issue 9 months ago • 3 comments

I've now hit enough bugs where someone wrote if event: rather than if event.is_set(): that I think Event.__bool__() should raise an error of some kind, likely NotImplementedError("Trio events cannot be treated as bools; consider using 'event.is_set()'").

I could be argued into def __bool__(self): return self.is_set() but disprefer this - "there should be one obvious way to do it". Thoughts?

I don't think there's as urgent a need on other classes, but we could consider e.g. Condition and Semaphore too...

Zac-HD avatar Apr 02 '25 03:04 Zac-HD

Since trio.Event is marked as a final class, mypy (at least) supports --enable-error-code=truthy-bool that will warn on if event. (actually I'm not even sure if that requires being marked as final)

I'm not sure how useful something at runtime is compared to that though.

A5rocks avatar Apr 02 '25 03:04 A5rocks

Seems very useful for everyone who doesn't use mypy, including those on other typecheckers! (like me, for example 😅)

Zac-HD avatar Apr 02 '25 04:04 Zac-HD

seems good, and should be a quick fix

jakkdl avatar Apr 02 '25 08:04 jakkdl

What about normal(expected) behaviour + showing a warning (warnings.warn) on console additionally ? I saw this in the case of lxml (ElementTree if I remember correctly).

AbduazizZiyodov avatar Aug 24 '25 18:08 AbduazizZiyodov

I think we should have a warning at first for deprecation reasons, but it should imitate the current behavior and return True.

But I suspect that having a proper traceback is nicer, plus warnings aren't harsh enough. And error->no error is trivial, no error->error requires a deprecation warning if we want to change this in the future.

A5rocks avatar Aug 24 '25 19:08 A5rocks