Alternate (Elm inspired) message handling using PEP 636 Structural Pattern Matching #2632
davetapley
started this conversation in
Ideas
Replies: 1 comment 1 reply
-
Having all messages go through a common method would create boilerplate code, which I want to avoid. It would also encourage Textual devs to implement their own ad-hoc message dispatch mechanism. Even if you are running on Python 3.10 and can use the match statement, it is still easy to get wrong. I take your point re refactoring, but changing the name of an event would likely necessitate changing the method name anyway. I'm guessing you haven't seen the new |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Context
The docs say for custom messages:
And reiterated in the section on handling messages:
Problem
Message handlers are very sensitive to refactoring:
Arguably comprehensive testing should catch such errors, but it still makes for an awkward developer experience.
How Elm does this
I am reminded of the message handling in Elm, which solves a similar problem but in a different way, specifically:
update
method, and:Proposal part 1
make renaming easier
Give
Widget
andApp
anupdate
method which would receive all messages.This would be called as well as the current magically named methods, allowing gradual adoption.
Inside the
update
method the developer could use PEP 636 Structural Pattern Matching as shown here to handle different messages.This would provide a common entry point for handlers, and so automated renaming of
Message
sub-classes wouldn't break handlers.Proposal part 2
strict mode for unhandled messages
Instead of implementing an
update
method, the developer could annotate handler methods with a decorator (and any appropriate method name). Textual would dispatch incoming messages to the appropriate handler.Textual could then (optionally) warn or throw when a
Widget
orApp
doesn't handle a message.The developer could then check whether the message is intentionally unhandled, and change bubbling or add a handler as appropriate.
Beta Was this translation helpful? Give feedback.
All reactions