-
Notifications
You must be signed in to change notification settings - Fork 786
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Decorator madness #4205
Open
willmcgugan
wants to merge
29
commits into
main
Choose a base branch
from
decorator-madness
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Decorator madness #4205
Changes from 21 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
6dac453
decorators ahoy
willmcgugan b28d420
restore calculator
willmcgugan 115e6d8
Add validate decorator
willmcgugan 61f3480
Merge branch 'main' into decorator-madness
willmcgugan 36f94b7
typing, remove print
willmcgugan 78b8313
icon emoji
willmcgugan 66074e8
test fix
willmcgugan facc087
removed import
willmcgugan adaacb0
snapshot fix
willmcgugan b3aa08b
command fix
willmcgugan 3685d55
type fixes docs
willmcgugan 70fbf4f
tests and docs
willmcgugan 5c02c0e
supliment test
willmcgugan f10d6eb
doc fix
willmcgugan d0ddc73
superfluous
willmcgugan 8963b38
examples
willmcgugan 8bfb48e
changelog
willmcgugan 4091760
word
willmcgugan 0cc9217
exampels in decorators
willmcgugan 444fc82
Merge branch 'main' into decorator-madness
willmcgugan fdbb80d
Merge branch 'main' into decorator-madness
willmcgugan 2053aec
Update docs/guide/reactivity.md
willmcgugan de6dc6b
Update src/textual/reactive.py
willmcgugan 871f633
Update src/textual/reactive.py
willmcgugan bc9654a
Update src/textual/reactive.py
willmcgugan 52a9484
Update src/textual/reactive.py
willmcgugan 2666e66
Update src/textual/reactive.py
willmcgugan 9aca190
remove init
willmcgugan c96125b
Update src/textual/reactive.py
willmcgugan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
from textual.app import App, ComposeResult | ||
from textual.color import Color | ||
from textual.containers import Horizontal | ||
from textual.reactive import reactive | ||
from textual.widgets import Input, Static | ||
|
||
|
||
class ComputedApp(App): | ||
CSS_PATH = "computed01.tcss" | ||
|
||
red = reactive(0) | ||
green = reactive(0) | ||
blue = reactive(0) | ||
color = reactive(Color.parse("transparent")) | ||
|
||
def compose(self) -> ComposeResult: | ||
yield Horizontal( | ||
Input("0", placeholder="Enter red 0-255", id="red"), | ||
Input("0", placeholder="Enter green 0-255", id="green"), | ||
Input("0", placeholder="Enter blue 0-255", id="blue"), | ||
id="color-inputs", | ||
) | ||
yield Static(id="color") | ||
|
||
@color.compute # (1)! | ||
def _(self) -> Color: | ||
return Color(self.red, self.green, self.blue).clamped | ||
|
||
@color.watch # (2)! | ||
def _(self, color: Color) -> None: | ||
self.query_one("#color").styles.background = color | ||
|
||
def on_input_changed(self, event: Input.Changed) -> None: | ||
try: | ||
component = int(event.value) | ||
except ValueError: | ||
self.bell() | ||
else: | ||
if event.input.id == "red": | ||
self.red = component | ||
elif event.input.id == "green": | ||
self.green = component | ||
else: | ||
self.blue = component | ||
|
||
|
||
if __name__ == "__main__": | ||
app = ComputedApp() | ||
app.run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
from textual.app import App, ComposeResult | ||
from textual.containers import Horizontal | ||
from textual.reactive import reactive | ||
from textual.widgets import Button, RichLog | ||
|
||
|
||
class ValidateApp(App): | ||
CSS_PATH = "validate01.tcss" | ||
|
||
count = reactive(0) | ||
|
||
@count.validate # (1)! | ||
def _(self, count: int) -> int: | ||
"""Validate value.""" | ||
if count < 0: | ||
count = 0 | ||
elif count > 10: | ||
count = 10 | ||
return count | ||
|
||
def compose(self) -> ComposeResult: | ||
yield Horizontal( | ||
Button("+1", id="plus", variant="success"), | ||
Button("-1", id="minus", variant="error"), | ||
id="buttons", | ||
) | ||
yield RichLog(highlight=True) | ||
|
||
def on_button_pressed(self, event: Button.Pressed) -> None: | ||
if event.button.id == "plus": | ||
self.count += 1 | ||
else: | ||
self.count -= 1 | ||
self.query_one(RichLog).write(f"count = {self.count}") | ||
|
||
|
||
if __name__ == "__main__": | ||
app = ValidateApp() | ||
app.run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
from textual.app import App, ComposeResult | ||
from textual.color import Color, ColorParseError | ||
from textual.containers import Grid | ||
from textual.reactive import reactive | ||
from textual.widgets import Input, Static | ||
|
||
|
||
class WatchApp(App): | ||
CSS_PATH = "watch01.tcss" | ||
|
||
color = reactive(Color.parse("transparent")) | ||
|
||
def compose(self) -> ComposeResult: | ||
yield Input(placeholder="Enter a color") | ||
yield Grid(Static(id="old"), Static(id="new"), id="colors") | ||
|
||
@color.watch # (1)! | ||
def _(self, old_color: Color, new_color: Color) -> None: | ||
self.query_one("#old").styles.background = old_color | ||
self.query_one("#new").styles.background = new_color | ||
|
||
def on_input_submitted(self, event: Input.Submitted) -> None: | ||
try: | ||
input_color = Color.parse(event.value) | ||
except ColorParseError: | ||
pass | ||
else: | ||
self.query_one(Input).value = "" | ||
self.color = input_color | ||
|
||
|
||
if __name__ == "__main__": | ||
app = WatchApp() | ||
app.run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
|
@@ -163,6 +163,31 @@ A common use for this is to restrict numbers to a given range. The following exa | |||||||||
|
||||||||||
If you click the buttons in the above example it will show the current count. When `self.count` is modified in the button handler, Textual runs `validate_count` which performs the validation to limit the value of count. | ||||||||||
|
||||||||||
### Validate decorator | ||||||||||
|
||||||||||
In addition to the the naming convention, you can also define a validate method via a decorator. | ||||||||||
When in the class scope, reactives have a `validate` attribute which you can use to decorate any method and turn it into a validator. | ||||||||||
The following example replaces the naming convention with an equivalent decorator: | ||||||||||
|
||||||||||
=== "validate02.py" | ||||||||||
|
||||||||||
```python hl_lines="12-13" | ||||||||||
--8<-- "docs/examples/guide/reactivity/validate02.py" | ||||||||||
``` | ||||||||||
|
||||||||||
1. This makes the following method a validator for the `count` reactive. | ||||||||||
|
||||||||||
=== "Output" | ||||||||||
|
||||||||||
```{.textual path="docs/examples/guide/reactivity/validate02.py"} | ||||||||||
``` | ||||||||||
|
||||||||||
Note that when you use the decorator approach, the name of the method is not important. | ||||||||||
In the example above we use an underscore to indicate the method doesn't need to be referenced outside of Textual's reactivity system. | ||||||||||
|
||||||||||
A benefit of the decorator is that it is refactor friendly. | ||||||||||
If you were to use your IDEA to change the name of the decorator, it will also update the decorator. | ||||||||||
willmcgugan marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
||||||||||
## Watch methods | ||||||||||
|
||||||||||
Watch methods are another superpower. | ||||||||||
|
@@ -171,7 +196,7 @@ Watch method names begin with `watch_` followed by the name of the attribute, an | |||||||||
If the method accepts a single argument, it will be called with the new assigned value. | ||||||||||
If the method accepts *two* positional arguments, it will be called with both the *old* value and the *new* value. | ||||||||||
|
||||||||||
The following app will display any color you type in to the input. Try it with a valid color in Textual CSS. For example `"darkorchid"` or `"#52de44"`. | ||||||||||
The following app will display any color you type into the input. Try it with a valid color in Textual CSS. For example `"darkorchid"` or `"#52de44"`. | ||||||||||
|
||||||||||
=== "watch01.py" | ||||||||||
|
||||||||||
|
@@ -196,6 +221,24 @@ The following app will display any color you type in to the input. Try it with a | |||||||||
|
||||||||||
The color is parsed in `on_input_submitted` and assigned to `self.color`. Because `color` is reactive, Textual also calls `watch_color` with the old and new values. | ||||||||||
|
||||||||||
### Watch decorator | ||||||||||
|
||||||||||
Like validate methods, watch methods may also be defined via a decorator. | ||||||||||
The following examples replaces the naming convention (i.e. `watch_color`) with the equivalent decorator: | ||||||||||
|
||||||||||
=== "watch02.py" | ||||||||||
|
||||||||||
```python hl_lines="17 18" | ||||||||||
--8<-- "docs/examples/guide/reactivity/watch02.py" | ||||||||||
``` | ||||||||||
|
||||||||||
1. The decorator defines a watch method for the `color` reactive attribute. | ||||||||||
|
||||||||||
=== "Output" | ||||||||||
|
||||||||||
```{.textual path="docs/examples/guide/reactivity/watch02.py" press="d,a,r,k,o,r,c,h,i,d"} | ||||||||||
``` | ||||||||||
|
||||||||||
### When are watch methods called? | ||||||||||
|
||||||||||
Textual only calls watch methods if the value of a reactive attribute _changes_. | ||||||||||
|
@@ -311,15 +354,15 @@ Compute methods are the final superpower offered by the `reactive` descriptor. T | |||||||||
|
||||||||||
You could be forgiven in thinking this sounds a lot like Python's property decorator. The difference is that Textual will cache the value of compute methods, and update them when any other reactive attribute changes. | ||||||||||
|
||||||||||
The following example uses a computed attribute. It displays three inputs for each color component (red, green, and blue). If you enter numbers in to these inputs, the background color of another widget changes. | ||||||||||
The following example uses a computed attribute. It displays three inputs for each color component (red, green, and blue). If you enter numbers into these inputs, the background color of another widget changes. | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Suggested change
|
||||||||||
|
||||||||||
=== "computed01.py" | ||||||||||
|
||||||||||
```python hl_lines="25-26 28-29" | ||||||||||
--8<-- "docs/examples/guide/reactivity/computed01.py" | ||||||||||
``` | ||||||||||
|
||||||||||
1. Combines color components in to a Color object. | ||||||||||
1. Combines color components into a Color object. | ||||||||||
2. The watch method is called when the _result_ of `compute_color` changes. | ||||||||||
|
||||||||||
=== "computed01.tcss" | ||||||||||
|
@@ -345,6 +388,25 @@ When the result of `compute_color` changes, Textual will also call `watch_color` | |||||||||
|
||||||||||
It is best to avoid doing anything slow or CPU-intensive in a compute method. Textual calls compute methods on an object when _any_ reactive attribute changes. | ||||||||||
|
||||||||||
### Compute decorator | ||||||||||
|
||||||||||
Compute methods may also be defined by the `compute` decorator on reactives. | ||||||||||
The following examples replaces the naming convention with an equivalent decorator: | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
=== "computed02.py" | ||||||||||
|
||||||||||
```python hl_lines="25-26 29-30" | ||||||||||
--8<-- "docs/examples/guide/reactivity/computed02.py" | ||||||||||
``` | ||||||||||
|
||||||||||
1. Defines a compute method for `color`. | ||||||||||
2. Defines a watch method for `color`. | ||||||||||
|
||||||||||
=== "Output" | ||||||||||
|
||||||||||
```{.textual path="docs/examples/guide/reactivity/computed02.py"} | ||||||||||
``` | ||||||||||
|
||||||||||
## Setting reactives without superpowers | ||||||||||
|
||||||||||
You may find yourself in a situation where you want to set a reactive value, but you *don't* want to invoke watchers or the other super powers. | ||||||||||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.