Textualize/textual · error · TypeError
`after` argument must be an index or a TreeNode object to ad
Error message
`after` argument must be an index or a TreeNode object to add after
What it means
TypeError from TreeNode.add(): the `after` argument is neither an int index nor a TreeNode, so no insertion position can be derived.
Source
Thrown at src/textual/widgets/_tree.py:422
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"
)
text_label = self._tree.process_label(label)
node = self._tree._add_node(self, text_label, data)
node._expanded = expand
node._allow_expand = allow_expand
self._updates += 1
self._children.insert(insert_index, node)
self._tree._invalidate()
return node
def add_leaf(
self,
label: TextType,
data: TreeDataType | None = None,
*,View on GitHub (pinned to 06dbeef4bb)
Solutions
- Convert to int: `after=int(value)`.
- Pass the TreeNode instead of an identifier string.
Example fix
# before
node.add("item", after="1")
# after
node.add("item", after=int("1")) Defensive patterns
Strategy: type-guard
Validate before calling
if not isinstance(after, (int, TreeNode)):
after = None
node.add(label, after=after) 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, after=pos)
except TypeError:
node.add(label) Prevention
- Coerce string indices with int() at the boundary
- Type-annotate insertion helpers
When it happens
Trigger: `node.add("x", after=3.5)`, `after="2"`, `after=(1,)` or any non-int/non-TreeNode value.
Common situations: Index read from user input or JSON as a string; refactor changed the expected type.
Related errors
- `before` argument must be an index or a TreeNode object to a
- 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/b269009793c6020c.
Report an issue: GitHub.