The roll() function returns an Expression object. The .expr attribute provides access to the Abstract Syntax Tree (AST), allowing you to traverse and inspect the roll components.
Finding Operands
You can use d20.utils to find the leftmost or rightmost operands in a binary operation.
from d20 import roll, utils
binop = roll("1 + 2 + 3 + 4")
print(utils.leftmost(binop.expr)) # <Literal 1>
print(utils.rightmost(binop.expr)) # <Literal 4>
Searching the Tree
Use d20.utils.dfs (Depth-First Search) to find specific nodes (e.g., a specific die type) within the tree.
from d20 import roll, utils, Dice
mixed = roll("-1d8 + 4 - (3, 1d4)kh1")
root = mixed.expr
# Find the 1d4 node
d4_node = utils.dfs(root, lambda node: isinstance(node, Dice) and node.num == 1 and node.size == 4)
from d20 import roll, utils
binop = roll("1 + 2 + 3 + 4")
left = binop.expr
while left.children:
left = left.children[0]
print(left) # <Literal 1>
from d20 import utils
print(utils.leftmost(binop.expr))
print(utils.rightmost(binop.expr))