Skip to content

Reactivity

Textual's reactive attributes are attributes with superpowers. In this chapter we will look at how reactive attributes can simplify your apps.

Quote

With great power comes great responsibility.

— Uncle Ben

Reactive attributes

Textual provides an alternative way of adding attributes to your widget or App, which doesn't require adding them to your class constructor (__init__). To create these attributes import reactive from textual.reactive, and assign them in the class scope.

The following code illustrates how to create reactive attributes:

from textual.reactive import reactive
from textual.widget import Widget

class Reactive(Widget):

    name = reactive("Paul")  # (1)!
    count = reactive(0) # (2)!
    is_cool = reactive(True)  # (3)!
  1. Create a string attribute with a default of "Paul"
  2. Creates an integer attribute with a default of 0.
  3. Creates a boolean attribute with a default of True.

The reactive constructor accepts a default value as the first positional argument.

Information

Textual uses Python's descriptor protocol to create reactive attributes, which is the same protocol used by the builtin property decorator.

You can get and set these attributes in the same way as if you had assigned them in an __init__ method. For instance self.name = "Jessica", self.count += 1, or print(self.is_cool).

Dynamic defaults

You can also set the default to a function (or other callable). Textual will call this function to get the default value. The following code illustrates a reactive value which will be automatically assigned the current time when the widget is created:

from time import time
from textual.reactive import reactive
from textual.widget import Widget

class Timer(Widget):

    start_time = reactive(time)  # (1)!
  1. The time function returns the current time in seconds.

Typing reactive attributes

There is no need to specify a type hint if a reactive attribute has a default value, as type checkers will assume the attribute is the same type as the default.

You may want to add explicit type hints if the attribute type is a superset of the default type. For instance if you want to make an attribute optional. Here's how you would create a reactive string attribute which may be None:

    name: reactive[str | None] = reactive("Paul")

Smart refresh

The first superpower we will look at is "smart refresh". When you modify a reactive attribute, Textual will make note of the fact that it has changed and refresh automatically.

Information

If you modify multiple reactive attributes, Textual will only do a single refresh to minimize updates.

Let's look at an example which illustrates this. In the following app, the value of an input is used to update a "Hello, World!" type greeting.

from textual.app import App, ComposeResult
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Input


class Name(Widget):
    """Generates a greeting."""

    who = reactive("name")

    def render(self) -> str:
        return f"Hello, {self.who}!"


class WatchApp(App):
    CSS_PATH = "refresh01.css"

    def compose(self) -> ComposeResult:
        yield Input(placeholder="Enter your name")
        yield Name()

    def on_input_changed(self, event: Input.Changed) -> None:
        self.query_one(Name).who = event.value


if __name__ == "__main__":
    app = WatchApp()
    app.run()
Input {
    dock: top;
    margin-top: 1;
}

Name {
    height: 100%;
    content-align: center middle;
}

WatchApp ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ Textual ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ Hello, Textual!

The Name widget has a reactive who attribute. When the app modifies that attribute, a refresh happens automatically.

Information

Textual will check if a value has really changed, so assigning the same value wont prompt an unnecessary refresh.

Disabling refresh

If you don't want an attribute to prompt a refresh or layout but you still want other reactive superpowers, you can use var to create an attribute. You can import var from textual.reactive.

The following code illustrates how you create non-refreshing reactive attributes.

class MyWidget(Widget):
    count = var(0)  # (1)!
  1. Changing self.count wont cause a refresh or layout.

Layout

The smart refresh feature will update the content area of a widget, but will not change its size. If modifying an attribute should change the size of the widget, you can set layout=True on the reactive attribute. This ensures that your CSS layout will update accordingly.

The following example modifies "refresh01.py" so that the greeting has an automatic width.

from textual.app import App, ComposeResult
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Input


class Name(Widget):
    """Generates a greeting."""

    who = reactive("name", layout=True)  # (1)!

    def render(self) -> str:
        return f"Hello, {self.who}!"


class WatchApp(App):
    CSS_PATH = "refresh02.css"

    def compose(self) -> ComposeResult:
        yield Input(placeholder="Enter your name")
        yield Name()

    def on_input_changed(self, event: Input.Changed) -> None:
        self.query_one(Name).who = event.value


if __name__ == "__main__":
    app = WatchApp()
    app.run()
  1. This attribute will update the layout when changed.
Input {
    dock: top;
    margin-top: 1;
}

Name {
    width: auto;
    height: auto;
    border: heavy $secondary;
}

WatchApp ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ name ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ┏━━━━━━━━━━━━┓ Hello, name! ┗━━━━━━━━━━━━┛

If you type in to the input now, the greeting will expand to fit the content. If you were to set layout=False on the reactive attribute, you should see that the box remains the same size when you type.

Validation

The next superpower we will look at is validation, which can check and potentially modify a value you assign to a reactive attribute.

If you add a method that begins with validate_ followed by the name of your attribute, it will be called when you assign a value to that attribute. This method should accept the incoming value as a positional argument, and return the value to set (which may be the same or a different value).

A common use for this is to restrict numbers to a given range. The following example keeps a count. There is a button to increase the count, and a button to decrease it. The validation ensures that the count will never go above 10 or below zero.

from textual.app import App, ComposeResult
from textual.containers import Horizontal
from textual.reactive import reactive
from textual.widgets import Button, TextLog


class ValidateApp(App):
    CSS_PATH = "validate01.css"

    count = reactive(0)

    def validate_count(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 TextLog(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(TextLog).write(f"{self.count=}")


if __name__ == "__main__":
    app = ValidateApp()
    app.run()
#buttons {
    dock: top;
    height: auto;
}

ValidateApp ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔  +1  -1  ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁

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.

Watch methods

Watch methods are another superpower. Textual will call watch methods when reactive attributes are modified. Watch methods begin with watch_ followed by the name of the attribute. If the watch method accepts a positional argument, it will be called with the new assigned value. If the watch 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".

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.css"

    color = reactive(Color.parse("transparent"))  # (1)!

    def compose(self) -> ComposeResult:
        yield Input(placeholder="Enter a color")
        yield Grid(Static(id="old"), Static(id="new"), id="colors")

    def watch_color(self, old_color: Color, new_color: Color) -> None:  # (2)!
        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  # (3)!


if __name__ == "__main__":
    app = WatchApp()
    app.run()
  1. Creates a reactive color attribute.
  2. Called when self.color is changed.
  3. New color is assigned here.
Input {
    dock: top;
    margin-top: 1;
}

#colors {
    grid-size: 2 1;
    grid-gutter: 2 4;
    grid-columns: 1fr;
    margin: 0 1;
}

#old {
    height: 100%;
    border: wide $secondary;
}

#new {        
    height: 100%;
    border: wide $secondary;
}

WatchApp ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ darkorchid ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔

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.

When are watch methods called?

Textual only calls watch methods if the value of a reactive attribute changes. If the newly assigned value is the same as the previous value, the watch method is not called. You can override this behaviour by passing always_update=True to reactive.

Compute methods

Compute methods are the final superpower offered by the reactive descriptor. Textual runs compute methods to calculate the value of a reactive attribute. Compute methods begin with compute_ followed by the name of the reactive value.

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.

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.css"

    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")

    def compute_color(self) -> Color:  # (1)!
        return Color(self.red, self.green, self.blue).clamped

    def watch_color(self, color: Color) -> None:  # (2)
        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()
  1. Combines color components in to a Color object.
  2. The watch method is called when the result of compute_color changes.
#color-inputs {
    dock: top;
    height: auto;
}

Input {
    width: 1fr;
}

#color {
    height: 100%;
    border: tall $secondary;
}

ComputedApp ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ 0                   0                    0                     ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔ ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁

Note the compute_color method which combines the color components into a Color object. It will be recalculated when any of the red , green, or blue attributes are modified.

When the result of compute_color changes, Textual will also call watch_color since color still has the watch method superpower.

Note

Textual will first attempt to call the compute method for a reactive attribute, followed by the validate method, and finally the watch method.

Note

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.