Writing nodes
Declare sockets, write code through the context.
A node does two things: it declares its sockets and it writes its code in emit(ctx). It never stores code and never builds sockets by hand.
import bpy
from ....sockets.spec import Flow, String
from ...base_node import ScriptingBaseNode
class SNA_Node_Print(ScriptingBaseNode, bpy.types.Node):
"""Print a message."""
bl_idname = "SNA_Node_Print"
bl_label = "Print"
sn_inputs = [Flow(), String("text", "Text")]
sn_outputs = [Flow("next")]
def emit(self, ctx):
ctx.code(f"""
{ctx.helper("log")}({ctx.input("text")})
{ctx.flow("next")}
""")Put the file in nodes/categories/<category>/; the folder name becomes the add menu entry. Nodes are registered automatically. To ship nodes without changing Scripting Nodes itself, put them in a node package.
Sockets
Sockets are declared with helpers from sockets/spec.py. The first argument is the key: the stable identifier code uses (ctx.input("text")). The second is the label the user sees.
| Helper | Socket |
|---|---|
Flow(key="flow", label, kind="PROGRAM"), Logic(), Interface() | flow (diamond). kind sets the color and which flows connect: Program and Logic run code, Interface draws UI |
String, Boolean, Float, Integer | value with an editable default (default=) |
Vector(dimension=3), Color(alpha=False) | vectors and colors |
Data, BlendData, List | any value, Blender data, lists |
Icon(key="icon") | an icon id. Draw it with icon_argument(ctx) (nodes/_icon.py): icon='NAME' for a picked icon, icon_value=... for a connected one, None without |
Socket(idname, key, label) | a type chosen at runtime |
Options: default=, hide=True, enabled=False (removes the socket from the UI), dynamic=True (a group the user can add sockets to; read it with ctx.inputs(key)).
When sockets depend on properties or other nodes, override socket_specs() instead of the class lists:
def socket_specs(self):
return [Flow(), Socket(self.data_type, "value", "Value")], [Flow("next")]The base class creates, removes and reorders sockets to match, and keeps the links of sockets that survive (matched by key). It is re-checked on every change and rebuild.
Properties
Node properties are regular bpy.props. Every change rebuilds the add-on automatically, so no update= callbacks are needed. Properties listed in sn_header_props are drawn on the node; for anything else implement draw(self, context, layout).
Kinds of nodes
Value nodes
Nodes with only data sockets produce expressions. Set every output with ctx.output. The compiler adds parentheses where the expression is used.
def emit(self, ctx):
result = f"{ctx.input('a')} {OPERATORS[self.operation]} {ctx.input('b')}"
ctx.output("result", result)
ctx.output("int", f"int({result})")Flow nodes
Nodes with a flow input write statements with ctx.code. Templates look like the generated code. ctx.flow(key) is a placeholder for whatever is connected to that flow output, indented to the column it sits in. Put it on its own line. An unconnected flow becomes pass where Python needs a statement; an else: with nothing in it is dropped.
def emit(self, ctx):
ctx.code(f"""
if {ctx.input("condition")}:
{ctx.flow("then")}
else:
{ctx.flow("else")}
{ctx.flow("next")}
""")Values a flow node produces are set with ctx.output before ctx.code; they are available to everything after the node. Values that only exist inside a branch are passed to that flow:
def emit(self, ctx):
item, index = ctx.var("item"), ctx.var("index")
ctx.code(f"""
for {index}, {item} in enumerate({ctx.input("list")}):
{ctx.flow("loop", outputs={"item": item, "index": index})}
{ctx.flow("next")}
""")Using Item after the loop gives an error on the node that uses it instead of broken code.
Interface nodes
Interface flows draw UI. ctx.layout is the current layout; pass a new one to a sub-flow:
def emit(self, ctx):
row = ctx.var("row")
ctx.code(f"""
{row} = {ctx.layout}.row(align={ctx.input("align")})
{ctx.flow("content", layout=row)}
{ctx.flow("next")}
""")Root nodes
Operators, panels, events and properties exist on their own. Set sn_root = True and write module-level code with ctx.module. Classes defined at module level are registered automatically; anything else goes into ctx.on_register / ctx.on_unregister.
class SNA_Node_OnSave(ScriptingBaseNode, bpy.types.Node):
sn_root = True
sn_outputs = [Logic()]
def sn_names(self):
return [naming.Symbol("function", "on_save")]
def emit(self, ctx):
name = ctx.name("function")
ctx.imports("from bpy.app.handlers import persistent")
ctx.module(f"""
@persistent
def {name}(*args):
{ctx.flow("flow")}
""")
ctx.on_register(f"bpy.app.handlers.save_post.append({name})")
ctx.on_unregister(f"bpy.app.handlers.save_post.remove({name})")Use ctx.join(lines) to insert a list of (possibly multi-line, possibly placeholder-containing) code items, for example class attributes or optional methods:
ctx.module(f"""
class {ctx.name("class")}(bpy.types.Panel):
{ctx.join(attributes)}
def draw(self, context):
{ctx.flow("body", layout="self.layout")}
""")Nodes that are both
A node in a flow can also write module-level code that must exist even when the flow doesn't reach it. Implement emit_module(ctx) next to emit(ctx): the compiler calls it once per build, before the root nodes. The UI List node defines its UIList class there, so the class exists even when no panel draws the list yet.
Names
Names other code can refer to (classes, operator idnames, module-level functions and variables) are declared in sn_names() with the helpers in core/naming.py, and read with ctx.name(key). Other nodes and the UI read them with node.sn_name(key), e.g. a Button gets the operator's idname.
def sn_names(self):
label = naming.label(self) # custom node label, else the Label input
return [naming.Class("class", "OT", label), naming.Idname("idname", label)]Class("class", "OT", "Say Hello") becomes MY_ADDON_OT_say_hello and Idname becomes my_addon.say_hello; Symbol(key, base) is a function or variable name. All names of the add-on are claimed in one pass (trees by name, nodes by name) and only a collision adds a suffix (say_hello_2). Local variables come from ctx.var("row"): row, then row_2, never shadowing a module-level name or a parameter.
sn_order sorts root nodes in the module, lower first: global variables 10, everything else 50. A root whose code uses names another root defines at definition time needs a higher order.
Referencing other nodes
A field that points at another node (a variable, a property, an operator) is a Reference(...) annotation (core/references.py). It stores the target's node id in a hidden <field>_id property, so renaming the target or its tree never breaks it. The visible field is a search field listing the allowed nodes by label (the tree is added for nodes in other trees).
class SNA_Node_GetVariable(ScriptingBaseNode, bpy.types.Node):
var: Reference(VARIABLE_NODES, name="Variable", filter=usable_variable)
def socket_specs(self):
target = self.resolve_reference("var")
...
def draw(self, context, layout):
self.draw_reference(layout, "var") # search field + jump button
def emit(self, ctx):
target = ctx.resolve("var")
if target is None:
raise NodeError("Pick a variable")
ctx.output("value", f"{ctx.symbol(target, target.getter_name())}()")- The first argument lists the allowed
bl_idnames (nodes/_reference_types.py).filter(owner_node, target)narrows the choices further, e.g. local variables only in their own tree. - Targets show their
reference_label()if they define one (Operator: its Label input), else the node's label or name. - A deleted target keeps its id (undo brings the reference back); the field is drawn red and
resolvereturnsNone. - Nodes copied together (pasted into another tree, duplicated with their tree) reference each other's copies. A node duplicated next to its target keeps pointing at the original.
references.users(target)lists the nodes referencing a node. The sidebar shows them for the active node, the Data panel counts them.
ctx.symbol(node, name) returns an expression for a name defined by another node. For a node in another tree it adds from .<module> import name and returns name. Trees that import each other (directly or through others) would fail with that, so the compiler compiles them again importing each other as modules: from . import <module> as _<module>, used as _<module>.name and looked up when the code runs. Names used while a module is imported still can't go both ways.
Using properties
Property definitions live in lists, not nodes (settings/properties.py): the add-on's list, groups' lists and the lists of Operator / Preferences nodes. A node picks one with sn_property_references = {"prop": "BOOLEAN"}; the value is a picker category from core/properties.CATEGORIES (which types it offers) and the property's id is stored in prop_id. core/properties.find(id) returns where it lives; PropertyTargetMixin turns that into (data, name) for code. Properties of a node class are written with PropertyListMixin.annotations(ctx); add-on properties go to properties.py.
Errors
Raise NodeError("message") when the node isn't set up completely; the message is shown on the node and the node writes no code. Unexpected exceptions are caught too and shown the same way.
Shared building blocks
| Base / mixin | For |
|---|---|
PropertyListMixin (nodes/_property_list.py) | nodes with their own properties (Operator, Preferences): list, annotations, outputs |
PropertyTargetMixin (nodes/_property_target.py) | nodes that read, set or draw one property (custom or pasted Blender path) |
PropertyFieldNode (interface/_property_field.py) | UI fields drawing one property (Checkbox, Number Field, …) |
OperatorCallMixin (nodes/_operator_call.py) | nodes that call an operator, one socket per operator property |
event_node() (events/events.py) | app handler events in one line |
Checklist
bl_idnamenever changes after release (saved files reference it).- User text goes into code through
repr()({value!r}), never between quotes. - Multi-line code goes through
ctx.flow,ctx.joinorctx.code, never pasted into a template line. - Use
ctx.var()for local names; declare module-level names insn_names()and read them withctx.name(). - Run
python scripts/test.py: it adds, chains, compiles and loads every node.