Textualize/textual · error
KeyError(key)
Error message
KeyError(key)
What it means
Styles.__getitem__ raises KeyError when the key is not one of the known CSS rule names (RULE_NAMES_SET). The mapping-style access only supports actual style rule names like 'width', 'color', 'display', etc.
Source
Thrown at src/textual/css/styles.py:580
easing=easing,
on_complete=(
partial(self.node.app.call_later, on_complete)
if on_complete is not None
else None
),
level=level,
)
return None
def __eq__(self, styles: object) -> bool:
"""Check that Styles contains the same rules."""
if not isinstance(styles, StylesBase):
return NotImplemented
return self.get_rules() == styles.get_rules()
def __getitem__(self, key: str) -> object:
if key not in RULE_NAMES_SET:
raise KeyError(key)
return getattr(self, key)
def get(self, key: str, default: object | None = None) -> object:
return getattr(self, key) if key in RULE_NAMES_SET else default
def __len__(self) -> int:
return len(RULE_NAMES)
def __iter__(self) -> Iterator[str]:
return iter(RULE_NAMES)
def __contains__(self, key: object) -> bool:
return key in RULE_NAMES_SET
def keys(self) -> Iterable[str]:
return RULE_NAMES
def values(self) -> Iterable[object]:View on GitHub (pinned to 06dbeef4bb)
Solutions
- Use styles.get(key) which returns None/default for unknown keys
- Verify the key against the known rule names (styles.get_rules() keys or textual.css.styles constants)
- Fix typos in the rule name
Example fix
// before
value = styles['background'] # wrong name
// after
value = styles.get('background-color', None) Defensive patterns
Strategy: type-guard
Validate before calling
from textual.css.styles import RULE_NAMES_SET
key = 'width'
if key not in RULE_NAMES_SET:
raise ValueError(f'unknown style rule {key}') Type guard
from textual.css.styles import RULE_NAMES_SET
def is_style_rule(key: str) -> bool:
return key in RULE_NAMES_SET Try / catch
try:
value = styles[key]
except KeyError:
value = None # or styles.get(key) Prevention
- Prefer styles.get(key) for dynamic access
- Whitelist keys against RULE_NAMES_SET before indexing
- Fix typos in rule names
When it happens
Trigger: styles['widht'] (typo), styles['some_custom_name'], or accessing via a name that is a Python attribute but not a registered rule. Note: use styles.get(key) for a None-safe lookup.
Common situations: Iterating/generic code that reads arbitrary keys from a Styles object; typos in rule names; assuming any Styles property is addressable via [] access.
Related errors
- No mode called {mode!r}
- invalid value for display (received {new_val!r}, expected {f
- invalid value for visibility (received {new_value!r}, expect
- Can't animate attribute {attribute!r} on {obj!r}; attribute
- Don't know how to animate {value!r}; Can only animate <int>,
AI-assisted analysis of Textualize/textual@06dbeef4bb (2026-08-27).
Data as JSON: /api/errors/0af39341429427e2.
Report an issue: GitHub.