Skip to content

node

Node.

This module defines the Node class and related types for workflow graphs.

Node dataclass

A node within a container (graph or group).

Source code in client/ayon_workflow/workflow_editor/node.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
@dataclass
class Node:
    """A node within a container (graph or group)."""

    plugin_ref: PluginRef
    name: str
    label: Optional[str] = None
    static_values: Dict[str, Any] = field(default_factory=dict)
    input_connections: Dict[str, Union[NodeConnection,
        List[NodeConnection], None]] = field(
            default_factory=dict
    )

    ui: Optional[ui_utils.UiNodeMetadata] = None
    metadata: Dict[str, Any] = field(default_factory=dict)

    def __post_init__(self) -> None:
        plugin_desc = self.get_plugin_desc()
        self._multi_input_names = []

        for plg_in in plugin_desc.inputs:
            name = plg_in.name
            self.static_values.setdefault(name, get_input_default(plg_in))
            if is_multi_connection_input(plg_in):
                self._multi_input_names.append(name)
                self.input_connections.setdefault(name, [])
            else:
                self.input_connections.setdefault(name, None)

        self._outputs = dict.fromkeys(
            [plg_out.name for plg_out in plugin_desc.outputs]
        )

        # Mandatory revert output slot for revert features.
        self._outputs["revert"] = None

    def get_plugin_desc(self) -> WorkflowNode:
        plugins = PluginRegistry().plugin_list()
        for name, plugin_desc in plugins.items():
            if (
                name == self.plugin_ref.name
                # TODO: check backward-compatibility here.
                and plugin_desc.version == self.plugin_ref.version
            ):
                return plugin_desc

        raise ValueError(f"Unknown plugin: {self.plugin_ref}")

    def __str__(self) -> str:
        return f"<Node {self.label} ({self.plugin_ref})>"

    def __setitem__(self, input_name: str, static_value: object):
        """Set node input static value."""
        if input_name not in self.inputs:
            raise KeyError(
                f"Invalid input name {input_name} for node {self}. "
                f"Available inputs are: {sorted(self.inputs)}"
            )

        # TODO: bring ¸input type validation against plugin_desc here.
        self.static_values[input_name] = static_value

    def __getitem__(self, input_name: str) -> object:
        """Get node input (static value or connection)."""
        if input_name not in self.inputs:
            raise KeyError(
                f"Invalid input name {input_name} for node {self}. "
                f"Available inputs are: {sorted(self.inputs)}"
            )

        return (
            # input comes from an inward node connection
            self.input_connections.get(input_name)
            # or is it set as static value ?
            or self.static_values[input_name]
        )

    @property
    def display_name(self) -> str:
        return self.label or self.name

    @property
    def inputs(self) -> Tuple:
        return tuple(self.input_connections.keys())

    @property
    def outputs(self) -> Tuple[str]:
        return tuple(self._outputs.keys())

    @property
    def node_type(self) -> str:
        return self.plugin_ref.name

    def _set_input(
        self, origin_node_name: str, origin_output_name: str, input_name: str
    ) -> None:
        if input_name not in self.inputs:
            raise ValueError(
                f"Cannot connect {origin_node_name}.{origin_output_name} "
                f"to {self}.{input_name}. Provided input does "
                f"not exist in {self}."
            )

        # TODO: bring ¸input type validation against node output type here.
        node_connection = NodeConnection(
            origin_node_name=origin_node_name,
            origin_node_output=origin_output_name,
        )

        if input_name in self._multi_input_names:
            self.input_connections[input_name].append(node_connection)
        else:
            self.input_connections[input_name] = node_connection

    def connect(
        self,
        output_name: str,
        destination_node: "Node",
        destination_input_name: str,
    ):
        """Connect specific output to another node input."""
        if output_name not in self._outputs:
            raise ValueError(
                f"Provided output {output_name} does not exist in {self}. "
                f"Available outputs are {self._outputs.keys()}"
            )

        if destination_node is self:
            raise ValueError(f"Cannot connect node to itself {self}.")

        # Actual implementation is to register
        # current node as destination node input.
        destination_node._set_input(
            self.name, output_name, destination_input_name
        )

    def disconnect_input(self,
            input_name: str,
            input_idx: int = -1,
        ):
        """Reset connection of incoming input."""
        if (
            input_name not in self.inputs
            or not self.input_connections[input_name]
        ):
            return

        if input_name not in self._multi_input_names:
            self.input_connections[input_name] = None
            return

        try:
            self.input_connections[input_name].pop(input_idx)
        except IndexError:
            return

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "Node":
        data = serialization.deserialize_from_primitive(data)

        # Backward compatible with previous serialization method.
        # TODO remove legacy serialization format support in a future version.
        if isinstance(data, dict):
            logger.warning("Node.from_dict: using legacy serialization format")
            input_connections = {}
            for key, value in data.get("input_connections", {}).items():
                if isinstance(value, list):
                    value = [NodeConnection(**val) for val in value]
                elif value:
                    value = NodeConnection(**value)

                input_connections[key] = value

            return cls(
                name=data["name"],
                plugin_ref=PluginRef(**data["plugin_ref"]),
                label=data.get("label"),
                static_values=data.get("static_values", {}),
                input_connections=input_connections,
                ui=data.get("ui"),
            )

        if not isinstance(data, cls):
            raise TypeError(
                f"Node.from_dict expected to deserialize a {cls.__name__} "
                f"instance, but got {type(value).__name__!r} instead."
            )

        return data

__getitem__(input_name)

Get node input (static value or connection).

Source code in client/ayon_workflow/workflow_editor/node.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def __getitem__(self, input_name: str) -> object:
    """Get node input (static value or connection)."""
    if input_name not in self.inputs:
        raise KeyError(
            f"Invalid input name {input_name} for node {self}. "
            f"Available inputs are: {sorted(self.inputs)}"
        )

    return (
        # input comes from an inward node connection
        self.input_connections.get(input_name)
        # or is it set as static value ?
        or self.static_values[input_name]
    )

__setitem__(input_name, static_value)

Set node input static value.

Source code in client/ayon_workflow/workflow_editor/node.py
151
152
153
154
155
156
157
158
159
160
def __setitem__(self, input_name: str, static_value: object):
    """Set node input static value."""
    if input_name not in self.inputs:
        raise KeyError(
            f"Invalid input name {input_name} for node {self}. "
            f"Available inputs are: {sorted(self.inputs)}"
        )

    # TODO: bring ¸input type validation against plugin_desc here.
    self.static_values[input_name] = static_value

connect(output_name, destination_node, destination_input_name)

Connect specific output to another node input.

Source code in client/ayon_workflow/workflow_editor/node.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def connect(
    self,
    output_name: str,
    destination_node: "Node",
    destination_input_name: str,
):
    """Connect specific output to another node input."""
    if output_name not in self._outputs:
        raise ValueError(
            f"Provided output {output_name} does not exist in {self}. "
            f"Available outputs are {self._outputs.keys()}"
        )

    if destination_node is self:
        raise ValueError(f"Cannot connect node to itself {self}.")

    # Actual implementation is to register
    # current node as destination node input.
    destination_node._set_input(
        self.name, output_name, destination_input_name
    )

disconnect_input(input_name, input_idx=-1)

Reset connection of incoming input.

Source code in client/ayon_workflow/workflow_editor/node.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def disconnect_input(self,
        input_name: str,
        input_idx: int = -1,
    ):
    """Reset connection of incoming input."""
    if (
        input_name not in self.inputs
        or not self.input_connections[input_name]
    ):
        return

    if input_name not in self._multi_input_names:
        self.input_connections[input_name] = None
        return

    try:
        self.input_connections[input_name].pop(input_idx)
    except IndexError:
        return

NodeConnection dataclass

A connection to a specific node.

Source code in client/ayon_workflow/workflow_editor/node.py
81
82
83
84
85
86
@dataclass
class NodeConnection:
    """A connection to a specific node."""

    origin_node_name: str
    origin_node_output: str

PluginRef dataclass

A reference to a Plugin (name + version).

Source code in client/ayon_workflow/workflow_editor/node.py
89
90
91
92
93
94
95
96
97
@dataclass
class PluginRef:
    """A reference to a Plugin (name + version)."""

    name: str
    version: str

    def __str__(self) -> str:
        return f"{self.name}@{self.version}"

get_input_default(input_def)

Get the default value for a plugin input definition.

For array inputs without an explicit default, returns an empty list. For other inputs, returns the explicit default or None.

Parameters:

Name Type Description Default
input_def InputAttribute

Plugin input definition.

required

Returns:

Type Description
Any

The default value for the input.

Source code in client/ayon_workflow/workflow_editor/node.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def get_input_default(input_def: InputAttribute) -> Any:
    """Get the default value for a plugin input definition.

    For array inputs without an explicit default, returns an empty list.
    For other inputs, returns the explicit default or None.

    Args:
        input_def: Plugin input definition.

    Returns:
        The default value for the input.
    """
    if input_def.default is None and is_array_input(input_def):
        return []

    return input_def.default

is_array_input(input_def)

Check if an input definition represents an array type.

This function examines the input definition to determine if it should be treated as an array parameter. It supports modern List[X] type hints (e.g., List[str], List[int]).

Uses typing.get_origin() for Python 3.9+ compatibility to detect generic List types.

Parameters:

Name Type Description Default
input_def InputAttribute

Plugin input definition.

required

Returns:

Type Description
bool

True if the input is an array type, False otherwise.

Source code in client/ayon_workflow/workflow_editor/node.py
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def is_array_input(input_def: InputAttribute) -> bool:
    """Check if an input definition represents an array type.

    This function examines the input definition to determine if it should
    be treated as an array parameter. It supports modern List[X] type hints
    (e.g., List[str], List[int]).

    Uses typing.get_origin() for Python 3.9+ compatibility to detect
    generic List types.

    Args:
        input_def: Plugin input definition.

    Returns:
        True if the input is an array type, False otherwise.
    """
    # Check type field - can be a Python type (like list) or a string
    input_type = input_def.type
    if input_type is not None:
        # Direct list type check
        if input_type is list:
            return True
        # Check for List[X] generic type using typing.get_origin()
        origin = get_origin(input_type)
        if origin in (list, List):
            return True

    return False

is_multi_connection_input(input_def)

Check if an input definition represents a multi connection input.

Source code in client/ayon_workflow/workflow_editor/node.py
24
25
26
27
def is_multi_connection_input(input_def: InputAttribute) -> bool:
    """Check if an input definition represents a multi connection input.
    """
    return bool(input_def.allow_multi_connection)