Textualize/textual · error · TypeError
`before` argument must be an index or a TreeNode object to a
Error message
`before` argument must be an index or a TreeNode object to add before
What it means
TypeError from TreeNode.add(): the `before` argument is neither an int nor a TreeNode — only those two types encode an insertion position.
Source
Thrown at src/textual/widgets/_tree.py:405
provided a `AddNodeError` will be raised.
"""
if before is not None and after is not None:
raise AddNodeError("Unable to add a node both before and after a node")
insert_index: int = len(self.children)
if before is not None:
if isinstance(before, int):
insert_index = before
elif isinstance(before, TreeNode):
try:
insert_index = self.children.index(before)
except ValueError:
raise AddNodeError(
"The node specified for `before` is not a child of this node"
)
else:
raise TypeError(
"`before` argument must be an index or a TreeNode object to add before"
)
if after is not None:
if isinstance(after, int):
insert_index = after + 1
if after < 0:
insert_index += len(self.children)
elif isinstance(after, TreeNode):
try:
insert_index = self.children.index(after) + 1
except ValueError:
raise AddNodeError(
"The node specified for `after` is not a child of this node"
)
else:
raise TypeError(
"`after` argument must be an index or a TreeNode object to add after"View on GitHub (pinned to 06dbeef4bb)
Solutions
- Pass an int index (`before=0`) or a TreeNode instance.
- Check the argument order: positional args are (label, data, before, after) — a misordered call can land a string in `before`.
Example fix
# before
node.add("item", before="node-1")
# after
node.add("item", before=tree.get_node_by_id("node-1")) Defensive patterns
Strategy: type-guard
Validate before calling
from textual.widgets._tree import TreeNode
if not isinstance(before, (int, TreeNode)):
raise TypeError('before must be int or TreeNode') Type guard
from textual.widgets._tree import TreeNode
def is_position(n: object) -> bool:
return isinstance(n, (int, TreeNode)) Try / catch
try:
node.add(label, before=pos)
except TypeError:
node.add(label) Prevention
- Convert user-supplied indices with int()
- Run a type checker (mypy) over tree insertion code
When it happens
Trigger: `node.add("x", before="first")`, `before=[0]`, or passing a label/other object where a position was expected.
Common situations: API confusion — passing a label string or an index wrapped in a list/tuple; refactors that changed the parameter type.
Related errors
- `after` argument must be an index or a TreeNode object to ad
- Unable to add a node both before and after a node
- The node specified for `before` is not a child of this node
- The node specified for `after` is not a child of this node
- {self.name} must be a str
AI-assisted analysis of Textualize/textual@06dbeef4bb (2026-08-27).
Data as JSON: /api/errors/c060500684864742.
Report an issue: GitHub.