Skip to content

Group

Bases: Node

Source code in core/nodeclass.py
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
class Group(Node):

    def __init__(self, group_name: str, named_sockets: dict = {}, **sockets):
        """ Node Group

        > Node Group

        Create a node 'Group' with the tree provided with 'group_name' argument.

        The sockets can be initialized either using the sockets dictionary or using they snake_case name
        as kwargs arguments.

        ``` python
        # Create a utility group
        with GeoNodes("Add two values", is_group=True):

            a = Float(0, "a")
            b = Float(0, "b")

            (a + b).out("Sum")

        # A node calling the utility group
        with GeoNodes("Call a group"):

            Geometry().out()

            c = Group("Add two values", {'a': Float(10, 'a'), 'b': Float(10, 'b')}).sum
            node = Group("Add two values")

            node.a = 100
            node.b = 200

            c.out("c")
            node._out.out("d")
        ```

        Parameters
        ----------
        group_name : str
            name of the group to use

        named_sockets : dict
            sockets initialization values

        **sockets : dict, default={}
            sockets  initialization with their snake_case name

        Returns
        -------
        Node Group
        """

        tree = Tree.current_tree()

        # ----------------------------------------------------------------------------------------------------
        # Get the node group by its name
        # ----------------------------------------------------------------------------------------------------

        spec = utils.get_available_groups(tree._btree.bl_idname).get(group_name, {})
        node_tree = blender.load_node_group(spec)
        if node_tree is None:
            raise NodeError(f"Impossible to find the group named '{group_name}'")

        # ----------------------------------------------------------------------------------------------------
        # Super init
        # ----------------------------------------------------------------------------------------------------

        super().__init__('Group', named_sockets=named_sockets, node_tree=node_tree, **sockets)

    # ----------------------------------------------------------------------------------------------------
    # Prefixed instantiation
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def Prefix(cls, prefix, group_name, named_sockets={}, **sockets):
        """ Call a Group with a prefixed named.

        > Node Group

        Using a prefix for groups of the same type can be usefull in big projects with
        a lot of groups.

        ``` python
        # Prefix used to identifiy utility groups
        UTIL = "UTIL"

        # Create a group utility
        with GeoNodes("Add two values", prefix=UTIL, is_group=True):

            a = Float(0, "a")
            b = Float(0, "b")

            (a + b).out("Sum")

        with GeoNodes("Call a group"):

            Geometry().out()

            # Call the the prefixed utility
            c = Group.Prefix(UTIL, "Add two values", {'a': Float(10, 'a'), 'b': Float(10, 'b')}).sum

            # Call the the prefixed utility
            node = Group.Prefix(UTIL, "Add two values")

            node.a = 100
            node.b = 200

            c.out("c")
            node._out.out("d")
        ```

        Parameters
        ----------
        prefix : str
            prefix

        group_name : str
            name of the group to use

        sockets : dict
            sockets initialization values

        **sockets : dict, default={}
            sockets  initialization with their snake_case name

        Returns
        -------
        Node Group
        """
        return cls(f"{str(prefix)} {group_name}", named_sockets=named_sockets, **sockets)

    # ====================================================================================================
    # Add a group as a class method
    # ====================================================================================================

    @staticmethod
    def add_method(
        group_name      : str, 
        target_class    : type, 
        *,
        func_name       : str = None,
        self_attr       : str = None,
        ret_class       : type = None, 
        prefix          : str = "",
        **fixed):
        """ Add a method calling the Group.

        The argument self_attr is the attribute to use to plug the node socket used as self:
        - None : the method is implemented as static method
        - "" : self is used directly
        - other = getattr(self, self_name) is plugged

        Parameters
        ----------
        group_name : str
            name of the Group

        target_class : type
            class to add the method to

        func_name : str, optional
            name of the method to create (snae case version of group name if None) default=None.

        self_attr : str, optional
            self name attribute name default=None.

        ret_class : type, optional
            class to use to transtype the output socket default=None.

        prefix : str, optional
            group prefix default="".

        self_attr : Any, optional
            which attr default=None.

        fixed : dict
            fixed values for sockets        

        """

        # ---------------------------------------------------------------------------
        # Get the node tree
        # ---------------------------------------------------------------------------

        if isinstance(group_name, bpy.types.NodeTree):
            btree = group_name
            group_name = btree.name
            full_name = btree.name

        else:
            pref = str(prefix)
            if pref != "":
                pref = pref + " "
            full_name = pref + group_name
            btree = bpy.data.node_groups.get(full_name)
            if btree is None:
                raise NodeError(f"Impossible to find the Group named '{full_name}'")

        # ---------------------------------------------------------------------------
        # The 3 possible calls
        # ---------------------------------------------------------------------------

        def self_method(self_, *args, **kwargs):
            node = Group(btree.name)
            return node.method_call(self_, *args, ret_class=ret_class, **kwargs, **fixed)

        def attr_method(self_, *args, **kwargs):
            node = Group(btree.name)
            return node.method_call(getattr(self_, self_attr), *args, ret_class=ret_class, **kwargs, **fixed)

        def static(*args, **kwargs):
            node = Group(btree.name)
            return node.method_call(*args, ret_class=ret_class, **kwargs, **fixed)

        # ---------------------------------------------------------------------------
        # Add the method to the class
        # ---------------------------------------------------------------------------

        if func_name is None:
            func_name = utils.snake_case(group_name)

        if func_name in dir(target_class):
            #raise NodeError(f"Impossible to add Node method '{func_name}'. This function already exists in class {target_class}.")
            print(f"CAUTION: the method '{func_name}' (implementing group '{full_name}') already exists in class {target_class}.")

        if self_attr is None:            
            setattr(target_class, func_name, staticmethod(static))

        elif self_attr.lower() in ["", "self"]:
            setattr(target_class, func_name, self_method)

        else:
            setattr(target_class, func_name, attr_method)

_out property

Returns the first enabled output socket.

Returns:

Type Description
Socket

first enabled output socket

Prefix(prefix, group_name, named_sockets={}, **sockets) classmethod

Call a Group with a prefixed named.

Node Group

Using a prefix for groups of the same type can be usefull in big projects with a lot of groups.

# Prefix used to identifiy utility groups
UTIL = "UTIL"

# Create a group utility
with GeoNodes("Add two values", prefix=UTIL, is_group=True):

    a = Float(0, "a")
    b = Float(0, "b")

    (a + b).out("Sum")

with GeoNodes("Call a group"):

    Geometry().out()

    # Call the the prefixed utility
    c = Group.Prefix(UTIL, "Add two values", {'a': Float(10, 'a'), 'b': Float(10, 'b')}).sum

    # Call the the prefixed utility
    node = Group.Prefix(UTIL, "Add two values")

    node.a = 100
    node.b = 200

    c.out("c")
    node._out.out("d")

Parameters:

Name Type Description Default
prefix str

prefix

required
group_name str

name of the group to use

required
sockets dict

sockets initialization values

{}
**sockets dict

sockets initialization with their snake_case name

{}

Returns:

Type Description
Node Group
Source code in core/nodeclass.py
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
@classmethod
def Prefix(cls, prefix, group_name, named_sockets={}, **sockets):
    """ Call a Group with a prefixed named.

    > Node Group

    Using a prefix for groups of the same type can be usefull in big projects with
    a lot of groups.

    ``` python
    # Prefix used to identifiy utility groups
    UTIL = "UTIL"

    # Create a group utility
    with GeoNodes("Add two values", prefix=UTIL, is_group=True):

        a = Float(0, "a")
        b = Float(0, "b")

        (a + b).out("Sum")

    with GeoNodes("Call a group"):

        Geometry().out()

        # Call the the prefixed utility
        c = Group.Prefix(UTIL, "Add two values", {'a': Float(10, 'a'), 'b': Float(10, 'b')}).sum

        # Call the the prefixed utility
        node = Group.Prefix(UTIL, "Add two values")

        node.a = 100
        node.b = 200

        c.out("c")
        node._out.out("d")
    ```

    Parameters
    ----------
    prefix : str
        prefix

    group_name : str
        name of the group to use

    sockets : dict
        sockets initialization values

    **sockets : dict, default={}
        sockets  initialization with their snake_case name

    Returns
    -------
    Node Group
    """
    return cls(f"{str(prefix)} {group_name}", named_sockets=named_sockets, **sockets)

__init__(group_name, named_sockets={}, **sockets)

Node Group

Node Group

Create a node 'Group' with the tree provided with 'group_name' argument.

The sockets can be initialized either using the sockets dictionary or using they snake_case name as kwargs arguments.

# Create a utility group
with GeoNodes("Add two values", is_group=True):

    a = Float(0, "a")
    b = Float(0, "b")

    (a + b).out("Sum")

# A node calling the utility group
with GeoNodes("Call a group"):

    Geometry().out()

    c = Group("Add two values", {'a': Float(10, 'a'), 'b': Float(10, 'b')}).sum
    node = Group("Add two values")

    node.a = 100
    node.b = 200

    c.out("c")
    node._out.out("d")

Parameters:

Name Type Description Default
group_name str

name of the group to use

required
named_sockets dict

sockets initialization values

{}
**sockets dict

sockets initialization with their snake_case name

{}

Returns:

Type Description
Node Group
Source code in core/nodeclass.py
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
def __init__(self, group_name: str, named_sockets: dict = {}, **sockets):
    """ Node Group

    > Node Group

    Create a node 'Group' with the tree provided with 'group_name' argument.

    The sockets can be initialized either using the sockets dictionary or using they snake_case name
    as kwargs arguments.

    ``` python
    # Create a utility group
    with GeoNodes("Add two values", is_group=True):

        a = Float(0, "a")
        b = Float(0, "b")

        (a + b).out("Sum")

    # A node calling the utility group
    with GeoNodes("Call a group"):

        Geometry().out()

        c = Group("Add two values", {'a': Float(10, 'a'), 'b': Float(10, 'b')}).sum
        node = Group("Add two values")

        node.a = 100
        node.b = 200

        c.out("c")
        node._out.out("d")
    ```

    Parameters
    ----------
    group_name : str
        name of the group to use

    named_sockets : dict
        sockets initialization values

    **sockets : dict, default={}
        sockets  initialization with their snake_case name

    Returns
    -------
    Node Group
    """

    tree = Tree.current_tree()

    # ----------------------------------------------------------------------------------------------------
    # Get the node group by its name
    # ----------------------------------------------------------------------------------------------------

    spec = utils.get_available_groups(tree._btree.bl_idname).get(group_name, {})
    node_tree = blender.load_node_group(spec)
    if node_tree is None:
        raise NodeError(f"Impossible to find the group named '{group_name}'")

    # ----------------------------------------------------------------------------------------------------
    # Super init
    # ----------------------------------------------------------------------------------------------------

    super().__init__('Group', named_sockets=named_sockets, node_tree=node_tree, **sockets)

_lc(label=None, color=None)

Set node label and color.

This method returns self to be chained:

Parameters:

Name Type Description Default
label str

node label default=None.

None
color color

node color default=None.

None

Returns:

Type Description
self
Source code in core/nodeclass.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
def _lc(self, label=None, color=None):
    """ Set node label and color.

    This method returns self to be chained:

    Parameters
    ----------
    label : str, optional
        node label default=None.

    color : color, optional
        node color default=None.


    Returns
    -------
    self
    """
    self._label = label
    self._color = color
    return self    

_socket_created(socket, value=None)

Socket creation call back

Source code in core/nodeclass.py
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
def _socket_created(self, socket, value=None):
    """ Socket creation call back
    """

    from .geometry_class import Geometry

    # Store created sockets

    bsocket = utils.get_bsocket(socket)
    inout = 'OUTPUT' if bsocket.is_output else 'INPUT'

    d = self._created_sockets.get(inout, {})
    d[bsocket.name] = socket
    self._created_sockets[inout] = d

    # Geometry class

    if inout == 'INPUT' and SocketType(value).is_geometry:
        if value is None or isinstance(value, SocketType):
            self._geo_classes[bsocket.name] = Geometry
        else:
            self._geo_classes[bsocket.name] = type(value)

_to_socket(socket)

Wrap a Blender socket with the dynamic geometry class when known.

Source code in core/nodeclass.py
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
def _to_socket(self, socket):
    """Wrap a Blender socket with the dynamic geometry class when known.
    """
    bsocket = utils.get_bsocket(socket)

    geo_classes = self._geo_classes
    if self._is_paired_output and self._paired_input_node is not None:
        geo_classes = self._paired_input_node._geo_classes

    geo_class = geo_classes.get(bsocket.name) or self._geo_classes.get(bsocket.name)
    if geo_class is not None:
        return geo_class(bsocket)

    return utils.to_socket(bsocket)

add_method(group_name, target_class, *, func_name=None, self_attr=None, ret_class=None, prefix='', **fixed) staticmethod

Add a method calling the Group.

The argument self_attr is the attribute to use to plug the node socket used as self: - None : the method is implemented as static method - "" : self is used directly - other = getattr(self, self_name) is plugged

Parameters:

Name Type Description Default
group_name str

name of the Group

required
target_class type

class to add the method to

required
func_name str

name of the method to create (snae case version of group name if None) default=None.

None
self_attr str

self name attribute name default=None.

None
ret_class type

class to use to transtype the output socket default=None.

None
prefix str

group prefix default="".

''
self_attr Any

which attr default=None.

None
fixed dict

fixed values for sockets

{}
Source code in core/nodeclass.py
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
@staticmethod
def add_method(
    group_name      : str, 
    target_class    : type, 
    *,
    func_name       : str = None,
    self_attr       : str = None,
    ret_class       : type = None, 
    prefix          : str = "",
    **fixed):
    """ Add a method calling the Group.

    The argument self_attr is the attribute to use to plug the node socket used as self:
    - None : the method is implemented as static method
    - "" : self is used directly
    - other = getattr(self, self_name) is plugged

    Parameters
    ----------
    group_name : str
        name of the Group

    target_class : type
        class to add the method to

    func_name : str, optional
        name of the method to create (snae case version of group name if None) default=None.

    self_attr : str, optional
        self name attribute name default=None.

    ret_class : type, optional
        class to use to transtype the output socket default=None.

    prefix : str, optional
        group prefix default="".

    self_attr : Any, optional
        which attr default=None.

    fixed : dict
        fixed values for sockets        

    """

    # ---------------------------------------------------------------------------
    # Get the node tree
    # ---------------------------------------------------------------------------

    if isinstance(group_name, bpy.types.NodeTree):
        btree = group_name
        group_name = btree.name
        full_name = btree.name

    else:
        pref = str(prefix)
        if pref != "":
            pref = pref + " "
        full_name = pref + group_name
        btree = bpy.data.node_groups.get(full_name)
        if btree is None:
            raise NodeError(f"Impossible to find the Group named '{full_name}'")

    # ---------------------------------------------------------------------------
    # The 3 possible calls
    # ---------------------------------------------------------------------------

    def self_method(self_, *args, **kwargs):
        node = Group(btree.name)
        return node.method_call(self_, *args, ret_class=ret_class, **kwargs, **fixed)

    def attr_method(self_, *args, **kwargs):
        node = Group(btree.name)
        return node.method_call(getattr(self_, self_attr), *args, ret_class=ret_class, **kwargs, **fixed)

    def static(*args, **kwargs):
        node = Group(btree.name)
        return node.method_call(*args, ret_class=ret_class, **kwargs, **fixed)

    # ---------------------------------------------------------------------------
    # Add the method to the class
    # ---------------------------------------------------------------------------

    if func_name is None:
        func_name = utils.snake_case(group_name)

    if func_name in dir(target_class):
        #raise NodeError(f"Impossible to add Node method '{func_name}'. This function already exists in class {target_class}.")
        print(f"CAUTION: the method '{func_name}' (implementing group '{full_name}') already exists in class {target_class}.")

    if self_attr is None:            
        setattr(target_class, func_name, staticmethod(static))

    elif self_attr.lower() in ["", "self"]:
        setattr(target_class, func_name, self_method)

    else:
        setattr(target_class, func_name, attr_method)

as_tuple()

Returns the output sockets as a tuple

Used in nodes such a separate_xyz to get the 3 components in a tuple

v = Vector()

# Split without node label
x, y, z = v.xyz

# Split with label
x, y, z = v.separate_xyz()._lc("Size").as_tuple()

Returns:

Type Description
tuple

tuple of enabled sockets

Source code in core/nodeclass.py
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
def as_tuple(self):
    """ Returns the output sockets as a tuple

    Used in nodes such a separate_xyz to get the 3 components in a tuple

    ``` python
    v = Vector()

    # Split without node label
    x, y, z = v.xyz

    # Split with label
    x, y, z = v.separate_xyz()._lc("Size").as_tuple()
    ```

    Returns
    -------
    tuple
        tuple of enabled sockets

    """
    return tuple([socket for _, socket in self.get_sockets('OUTPUT')])

create_from_socket(in_out, socket, name=None, panel='', **props)

Create a new socket from a socket and link them

Parameters:

Name Type Description Default
in_out (INPUT, OUPUT)

input or output socket

'INPUT'
socket Socket | NodeSocket

socket to create from

required
panel str

creation panel default="".

''
props dict

additional properties

{}

Raises:

Type Description
- NodeError if impossible to create the socket

Returns:

Type Description
Socket

the created socket

Source code in core/nodeclass.py
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
def create_from_socket(self,
        in_out  : IN_OUT, 
        socket  : Socket,
        name    : str = None, 
        panel   : str="", **props) -> Socket:
    """ Create a new socket from a socket and link them

    Parameters
    ----------
    in_out : {'INPUT', 'OUPUT'}
        input or output socket

    socket : Socket | bpy.types.NodeSocket
        socket to create from

    panel : str, optional
        creation panel default="".

    props : dict
        additional properties


    Raises
    ------
    - NodeError if impossible to create the socket

    Returns
    -------
    Socket
        the created socket

    """

    # ---------------------------------------------------------------------------
    # Creation must be possible
    # ---------------------------------------------------------------------------

    assert in_out in ('INPUT', 'OUTPUT')

    if (in_out == 'INPUT' and not self._has_dyn_in) or (in_out == 'OUTPUT' and not self._has_dyn_out):
        raise NodeError(f"Impossible to create a {in_out} socket for node {self} (name '{name}').")

    bsocket = SocketType.get_bsocket(socket)
    if bsocket is None:
        raise NodeError(f"Invalid socket: {socket}.")

    if name is None:
        name = utils.get_default_name(socket)

    # ---------------------------------------------------------------------------
    # Tree interface
    # ---------------------------------------------------------------------------

    if self._use_interface:

        intf_in_out = self._interface_in_out[in_out]
        if intf_in_out is None:
            assert False, f"Shouldn't happen"

        isock = self._interface.create_socket(intf_in_out, name, socket_type=None, parent=self._tree.get_panel(panel), from_socket=bsocket, **props)
        if isock is None:
            raise NodeError(f"Impossible to create the {intf_in_out} socket named in Node {self}", name=name, **props)

        created = self.socket_by_identifier(in_out, isock.identifier)        

    # ---------------------------------------------------------------------------
    # Items
    # ---------------------------------------------------------------------------

    else:
        full_name = (ItemPath(panel) + name).long_name
        items_type = SocketType(bsocket).items_type

        # No arguments
        if self._bnode.bl_idname in ['GeometryNodeIndexSwitch']:
            self._items[in_out].new()

        # Name only
        elif self._bnode.bl_idname in ['GeometryNodeMenuSwitch']:
            self._items[in_out].new(full_name)

        # For each
        elif self._bnode.bl_idname == 'GeometryNodeForeachGeometryElementOutput':
            if utils.snake_case(panel) == "main":
                items = self._bnode.main_items
            else:
                items = self._bnode.generation_items
            items.new(items_type, full_name)

        # Name and data type
        else:
            try:
                self._items[in_out].new(items_type, full_name)
            except Exception as e:
                raise NodeError(f"Impossible to create the item '{full_name}' in Node ({self._bnode.bl_idname}), Socket type: '{items_type}': {str(e)}")

        sockets = self._bnode.inputs if in_out == 'INPUT' else self._bnode.outputs
        created = sockets[-2]

    # ---------------------------------------------------------------------------
    # Link and return
    # ---------------------------------------------------------------------------

    if bsocket.is_output:
        self._tree.link(bsocket, created)
    else:
        self._tree.link(created, bsocket)

    self._socket_created(created, value=socket)

    return created

create_socket(in_out, socket_type, name, panel='', **props)

Create a new socket.

Parameters:

Name Type Description Default
in_out (INPUT, OUPUT)

input or output socket

'INPUT'
socket_type str | Socket

type of socket to create

required
panel str

creation panel default="".

''
props dict

additional properties

{}

Raises:

Type Description
- NodeError if impossible to create the socket

Returns:

Type Description
Socket (output) or bpy.types.NodeSocket (input) : the created socket
Source code in core/nodeclass.py
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
def create_socket(self, 
        in_out      : IN_OUT, 
        socket_type : str | SocketType, 
        name        : str, 
        panel       : str="",
        **props) -> Socket:
    """ Create a new socket.

    Parameters
    ----------
    in_out : {'INPUT', 'OUPUT'}
        input or output socket

    socket_type : str | Socket
        type of socket to create

    panel : str, optional
        creation panel default="".

    props : dict
        additional properties


    Raises
    ------
    - NodeError if impossible to create the socket

    Returns
    -------
    Socket (output) or bpy.types.NodeSocket (input) : the created socket
    """

    # ---------------------------------------------------------------------------
    # Creation must be possible
    # ---------------------------------------------------------------------------

    assert in_out in ('INPUT', 'OUTPUT')
    if socket_type is None:
        assert self._bnode.bl_idname in constants.AUTO_INPUT_TYPE_NODES
        socket_type = SocketType(self._bnode.data_type)

    if (in_out == 'INPUT' and not self._has_dyn_in) or (in_out == 'OUTPUT' and not self._has_dyn_out):            
        raise NodeError(f"Impossible to create a {in_out} socket for node {self} (name '{name}').")

    # ---------------------------------------------------------------------------
    # Socket type and sub type
    # ---------------------------------------------------------------------------

    socket_type = SocketType(socket_type)
    creation_props = socket_type.set_props({**props})

    # ---------------------------------------------------------------------------
    # Tree interface
    # ---------------------------------------------------------------------------

    if self._use_interface:

        intf_in_out = self._interface_in_out[in_out]
        if intf_in_out is None:
            assert False, f"Shouldn't happen"

        isock = self._interface.create_socket(intf_in_out, name, socket_type, parent=self._tree.get_panel(panel), **creation_props)
        if isock is None:
            raise NodeError(f"Impossible to create the {intf_in_out} socket named in Node {self}", name=name, stype=str(socket_type), **creation_props)

        socket = self.socket_by_identifier(in_out, isock.identifier)

    # ---------------------------------------------------------------------------
    # Items
    # ---------------------------------------------------------------------------

    else:

        # For each
        if self._bnode.bl_idname == 'GeometryNodeForeachGeometryElementOutput':
            if utils.snake_case(panel) == "main":
                items = self._bnode.main_items
            else:
                items = self._bnode.generation_items
        else:
            items = self._items[in_out]

        full_name = (ItemPath(panel) + name).long_name
        # No argument
        if self._bnode.bl_idname in ['GeometryNodeIndexSwitch']:
            items.new()

        # One argument
        elif self._bnode.bl_idname in ['GeometryNodeMenuSwitch']:
            items.new(full_name)

        # Two arguments
        else:
            try:
                items.new(socket_type.items_type, full_name)
            except Exception as e:
                raise NodeError(
                    f"Impossible to create the socket '{full_name}' of type '{socket_type.items_type} "
                    f" in node [{self._bnode.bl_idname}].\n{str(e)}")

        io_socks = self._bnode.inputs if in_out == 'INPUT' else self._bnode.outputs
        socket = io_socks[-2]

        # Default on input socket for paired input nodes
        if in_out == 'OUTPUT' and self._is_paired_input:
            def_val = props.get('default', props.get('default_value', None))
            if def_val is not None:
                try:
                    self._inputs.by_name(full_name).default_value = def_val
                except Exception as e:
                    pass
                    #raise RuntimeError(f"Erreor setting default val <{def_val}>, Node {self}, {name=}, {full_name=}: {str(e)}")


    self._socket_created(socket, value=socket_type)

    return socket

data_type_from_value(value, param_name='data_type', on_error='DEFAULT')

Get the data_type from the value to plug on socket

Parameters:

Name Type Description Default
value

the value to set on the socket

required
param_name (data_type, input_type)

param name

'data_type'
on_error (HALT, NONE, DEFAULT)

what to do if not found

'HALT'

Returns:

Type Description
data_type

a valid data type

Source code in core/nodeclass.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
def data_type_from_value(self, value, param_name: str = 'data_type', on_error: str = 'DEFAULT'):
    """ Get the data_type from the value to plug on socket

    Parameters
    ----------
    value
        the value to set on the socket

    param_name : {'data_type', 'input_type'}
        param name

    on_error : {'HALT', 'NONE', 'DEFAULT'}
        what to do if not found


    Returns
    -------
    data_type
        a valid data type

    """
    return SocketType.get_data_type_for_node(value, self._bnode.bl_idname, param_name, on_error='DEFAULT')

get_signature(include=None, exclude=[], enabled_only=False, free_only=False, with_sockets=False)

Build the signature of the node.

Parameters:

Name Type Description Default
include list

sockets to include default=None.

None
exclude list

sockets to exclude default=[].

[]
enabled_only bool

(bool = True) : ignore disabled sockets

False
free_only bool

ignore linked sockets

False
with_sockets bool

include sockets default=False.

False

Returns:

Type Description
Signature
Source code in core/nodeclass.py
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
def get_signature(self, 
        include      : list = None, 
        exclude      : list = [], 
        enabled_only : bool = False, 
        free_only    : bool = False,
        with_sockets : bool = False) -> Signature:
    """ Build the signature of the node.

    Parameters
    ----------
    include : list, optional
        sockets to include default=None.

    exclude : list, optional
        sockets to exclude default=[].

    enabled_only
        (bool = True) : ignore disabled sockets

    free_only : bool, default=False
        ignore linked sockets

    with_sockets : bool, optional
        include sockets default=False.


    Returns
    -------
    Signature
    """

    sigs = []
    for in_out in ('INPUT', 'OUTPUT'):

        node_sockets = self.get_sockets(
            in_out, 
            include         = include, 
            exclude         = exclude, 
            enabled_only    = enabled_only, 
            free_only       = free_only)

        sig = {}
        #for name, socket in node_sockets.items():
        for name, socket in node_sockets:

            bsocket = utils.get_bsocket(socket)

            sig[name] = {
                'socket_type' : SocketType(bsocket),
                'identifier'  : bsocket.identifier,
            }

            if with_sockets:
                sig[name]['socket'] = socket

        sigs.append(sig)

    return Signature(*sigs)

get_socket(in_out, name, socket_type, enabled_only=True, free_only=False, halt=True)

Get a socket by a reference

Parameters:

Name Type Description Default
in_out (INPUT, OUTPUT)

input or output sockets

'INPUT'
name str | int | Socket

socket index, name, identifier or the socket itself

required
socket_type str

socket type

required
enabled_only bool

ignore disabled sockets default=True

True
free_only bool

ignore linked sockets default=False.

False
halt bool

raises an error if not found default=True.

True

Returns:

Type Description
Socket if found
Source code in core/nodeclass.py
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
def get_socket(self, 
        in_out       : IN_OUT, 
        name         : str | int | Socket, 
        socket_type  : str,
        enabled_only : bool = True, 
        free_only    : bool = False, 
        halt         : bool = True) -> Socket:
    """ Get a socket by a reference

    Parameters
    ----------
    in_out : {'INPUT', 'OUTPUT'}
        input or output sockets

    name : str | int | Socket
        socket index, name, identifier or the socket itself

    socket_type : str
        socket type

    enabled_only : bool
        ignore disabled sockets default=True

    free_only : bool, optional
        ignore linked sockets default=False.

    halt : bool, optional
        raises an error if not found default=True.


    Returns
    -------
    Socket if found
    """

    # The result is provided
    socket = utils.get_bsocket(name)
    if socket is not None:
        return socket

    # By its index
    if isinstance(name, int):
        return self.socket_by_index(in_out, name, enabled_only=enabled_only)

    # Let's try the identifier
    socket = self.socket_by_identifier(in_out, name, halt=False)
    if socket is not None:
        return socket

    # Utltimately : the socket name
    return self.socket_by_name(in_out, name, socket_type, enabled_only=enabled_only, free_only=free_only, halt = halt)

get_socket_default_name(in_out, value)

Get the socket default name from a value

Parameters:

Name Type Description Default
in_out (INPUT, OUTPUT)

for input or output socket

'INPUT'
value Any

the value to name

required
Source code in core/nodeclass.py
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
def get_socket_default_name(self, in_out: IN_OUT, value) -> str:
    """ Get the socket default name from a value

    Parameters
    ----------
    in_out : {'INPUT', 'OUTPUT'}
        for input or output socket

    value : Any
        the value to name

    """
    if SocketType(value).type == 'GEOMETRY':
        if in_out == 'OUTPUT' and self._bnode.bl_idname == "GeometryNodeForeachGeometryElementOutput":
            return "Geometry"

        return type(value).__name__

    return utils.get_default_name(value)

get_sockets(in_out, include=None, exclude=[], enabled_only=True, free_only=False, panel='')

Build a list of sockets.

Parameters:

Name Type Description Default
in_out (INPUT, OUTPUT)

input or output sockets

'INPUT'
include list

sockets to include default=None.

None
exclude list

sockets to exclude default=[].

[]
enabled_only bool

(bool = True) : ignore disabled sockets

True
free_only bool

(bool = False) : ignore linked sockets

False

Returns:

Type Description
list of sockets
Source code in core/nodeclass.py
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
def get_sockets(self, 
        in_out       : IN_OUT, 
        include      : list = None,
        exclude      : list = [],
        enabled_only : bool = True,
        free_only    : bool = False,
        panel        : str = "") -> list[(str, Socket)]:
    """ Build a list of sockets.

    Parameters
    ----------
    in_out : {'INPUT', 'OUTPUT'}
        input or output sockets

    include : list, optional
        sockets to include default=None.

    exclude : list, optional
        sockets to exclude default=[].

    enabled_only
        (bool = True) : ignore disabled sockets

    free_only
        (bool = False) : ignore linked sockets


    Returns
    -------
    list of sockets
    """

    assert(in_out in ('INPUT', 'OUTPUT'))

    # ====================================================================================================
    # Get from tree interface
    # ====================================================================================================

    if self._use_interface:

        intf_in_out = self._interface_in_out[in_out]
        if intf_in_out is None:
            return []

        isocks = self._interface.get_sockets(
            intf_in_out, 
            include      = include,
            exclude      = exclude,
            enabled_only = enabled_only,
            parent       = panel,
        )

        sockets = []
        for isock in isocks:
            path = ItemPath(isock) - ItemPath(panel)
            if in_out == 'INPUT':
                socket = self._bnode.inputs[isock.identifier]

                if free_only and not utils.is_free(socket):
                    continue

            else:
                socket = self._to_socket(self._bnode.outputs[isock.identifier])

            sockets.append((path.path, socket))

        return sockets

    # ====================================================================================================
    # No tree interface
    # ====================================================================================================

    sockets = []

    socks = self._inputs if in_out == 'INPUT' else self._outputs

    panel_path = ItemPath(panel).ranked_long_name

    for name, socket in socks:

        if in_out == 'INPUT' and free_only and not utils.is_free(socket):
            continue

        if panel_path != "" and not name.startswith(panel_path):
            continue

        names = (name, utils.snake_case(name))
        if include is not None:
            ok = False
            for iname in include:
                if iname in names:
                    ok = True
                    break
            if not ok:
                continue

        ok = True
        for iname in exclude:
            if iname in names:
                ok = False
                break
        if not ok:
            continue

        sockets.append((name, socket))

    return sockets

Link input sockets from another node

If from_node is None, the current input node is taken.

Sockets which has been set at initialization time and sockets already linked are ignored.

If from node is able to create output sockets, they are created, otherwise only the sockets with matching names and types are linked.

Parameters:

Name Type Description Default
from_node Node

node to get output sockets from

None
from_panel str

the panel to use in from_node

""
include list

sockets to include

None
exclude list

sockets to exclude

[]
panel str

panel to select input socket

""

Returns:

Type Description
self
Source code in core/nodeclass.py
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
def link_inputs(self,
    from_node   : Node = None,
    from_panel  : str = "",
    *,
    include     : list =  None,
    exclude     : list  = [],
    panel       : str = "",
    ):
    """ Link input sockets from another node

    If from_node is None, the current input node is taken.

    Sockets which has been set at initialization time and sockets already linked are ignored.

    If from node is able to create output sockets, they are created, otherwise only the sockets
    with matching names and types are linked.

    Parameters
    ----------
    from_node : Node, default=None
        node to get output sockets from

    from_panel : str, default=""
        the panel to use in from_node

    include : list, default=None
        sockets to include

    exclude : list, default=[]
        sockets to exclude

    panel : str, default=""
        panel to select input socket

    Returns
    -------
    self
    """

    # ---------------------------------------------------------------------------
    # The list of input sockets to link
    # ---------------------------------------------------------------------------

    if from_node is None:
        from_node = self._tree.get_input_node()
    elif from_node in ['GROUP', 'TREE']:
        from_node = self._tree.input_node

    in_sockets = self.get_sockets(
        'INPUT',
        include      = include,
        exclude      = exclude + self._link_ignore,
        enabled_only = True,
        free_only    = True,
        panel        = panel,
        )

    # ---------------------------------------------------------------------------
    # Create the links
    # ---------------------------------------------------------------------------

    for name, in_socket in in_sockets:

        path = ItemPath(from_panel) + name

        out_socket = from_node.socket_by_name('OUTPUT', path, SocketType(in_socket).type, halt=False)

        if out_socket is None:
            if from_node._has_dyn_out:
                out_socket = from_node.create_from_socket('OUTPUT', in_socket, name=path)

                # Copy the properties when both nodes have interface
                if self._use_interface and from_node._use_interface:
                    self._interface.copy_properties(
                        from_node._interface.by_identifier(out_socket._bsocket.identifier),
                        self._interface.by_identifier(in_socket.identifier)
                        )

        if out_socket is not None:
            self._tree.link(out_socket, in_socket)

    return self

Link output socket to another node

if to_node is None, the current output node is taken.

If from node is able to create output sockets, they are created, otherwise only the sockets with matchin names and types are linked.

Parameters:

Name Type Description Default
to_node Node

node to plug into

None
to_panel str

the panel to use in to_node

""
include list

sockets to include

None
exclude list

sockets to exclude

[]]
panel str

panel to select input socket in

""
Source code in core/nodeclass.py
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
def link_outputs(self,
    to_node     : Node = None,
    to_panel    : str = "",
    *,
    include     : list =  None,
    exclude     : list  = [],
    panel       : str = "",
    ):
    """ Link output socket to another node

    if to_node is None, the current output node is taken.

    If from node is able to create output sockets, they are created, otherwise only the sockets
    with matchin names and types are linked.

    Parameters
    ----------
    to_node : Node, default=None
        node to plug into

    to_panel : str, default=""
        the panel to use in to_node

    include : list, default=None
        sockets to include

    exclude : list, default=[]]
        sockets to exclude

    panel : str, default=""
        panel to select input socket in

    """

    # ---------------------------------------------------------------------------
    # The list of output sockets to link
    # ---------------------------------------------------------------------------

    if to_node is None:
        to_node = self._tree.get_output_node()

    out_sockets = self.get_sockets(
        'OUTPUT',
        include      = include,
        exclude      = exclude,
        enabled_only = True,
        panel        = panel,
        )

    # ---------------------------------------------------------------------------
    # Create the links
    # ---------------------------------------------------------------------------

    links = []

    for name, out_socket in out_sockets:

        path = (ItemPath(to_panel) + name).path

        in_socket = to_node.socket_by_name('INPUT', path, SocketType(out_socket).type, halt=False)

        if in_socket is None:
            if to_node._has_dyn_in:
                in_socket = to_node.create_from_socket('INPUT', out_socket, name=path)

        if in_socket is not None:
            self._tree.link(out_socket, in_socket)
            links.append((out_socket, in_socket))

    return links

Link panel input sockets from another node

If from_node is None, the current input node is taken.

see `link_inputs``

Call:

    return self.link_inputs(from_node=from_node, from_panel=panel, panel=panel)

Parameters:

Name Type Description Default
panel str

the panel to use in from_node and to select input sockets

required
from_node Node

node to get output sockets from

None

Returns:

Type Description
self
Source code in core/nodeclass.py
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
def link_panel(self, panel: str, from_node : Node = None):
    """ Link panel input sockets from another node

    If from_node is None, the current input node is taken.

    see `link_inputs``

    Call:

    ```python
        return self.link_inputs(from_node=from_node, from_panel=panel, panel=panel)
    ```

    Parameters
    ----------
    panel : str
        the panel to use in from_node and to select input sockets

    from_node : Node, default=None
        node to get output sockets from

    Returns
    -------
    self
    """
    if isinstance(panel, str):
        return self.link_inputs(from_node=from_node, from_panel=panel, panel=panel)

    for s in panel:
        self.link_panel(s, from_node=from_node)

    return self

method_call(*args, ret_class=None, **kwargs)

Link the input sockets with method arguments

Parameters:

Name Type Description Default
args tuple

values of the first sockets (but self_ if not None)

()
ret_class type

output class

None
kwargs dict

named sockets

{}

Returns:

Type Description
Socket

node._out

Source code in core/nodeclass.py
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
def method_call(self, *args, ret_class = None, **kwargs):
    """ Link the input sockets with method arguments

    Parameters
    ----------
    args : tuple
        values of the first sockets (but self_ if not None)

    ret_class : type
        output class

    kwargs : dict
        named sockets


    Returns
    -------
    Socket
        node._out

    """

    # ------------------------------------------------------------
    # Get the valid input sockets
    # ------------------------------------------------------------

    sockets = self.get_sockets('INPUT', enabled_only = False, free_only = False)

    # For error message
    sig = self.get_signature()
    ssocks = []
    for index, d in enumerate(sig.inputs):
        s = f"{utils.snake_case(d['name']):15s} : {SocketType(d['socket_type']).class_name}"
        if index < len(args):
            s += " (arg)"
        ssocks.append(s)
    valids = "\n- " + "\n- ".join(ssocks)

    # The number of arguments must not exceed the number of valid sockets
    n = len(args) + len(kwargs)
    if n > len(sockets):
        raise NodeError(
            f"Error when calling {self}: too many arguments.\n"
            f"The node has only {len(sockets)} input sockets but {n} arguments are provided.\n"
            f"Valid sockets are: {valids}\n")

    # ------------------------------------------------------------
    # Sockets set by arguments
    # ------------------------------------------------------------

    n = len(args)        
    arg_sockets = list(sockets[:n])
    remain      = list(sockets[n:])

    dones = []

    for (name, socket), arg in zip(arg_sockets, args):

        dones.append(f"{socket.name} <- <{arg}> (arg)")

        try:
            self.set_input_socket_value(socket, arg)

        except Exception as e:

            sdones = "\n - " + "\n - ".join(dones)

            raise NodeError(
                f"Error when calling '{self}': impossible to set the socket '{socket.name}' with value <{arg}>.\n"
                f"Valid sockets are: {valids}\n"
                f"Sockets successfully set:{sdones}")

    # ------------------------------------------------------------
    # Sockets set by key word arguments
    # ------------------------------------------------------------

    for name, value in kwargs.items():
        self.set_input_socket(name, value)

    # ------------------------------------------------------------
    # Done
    # ------------------------------------------------------------

    if ret_class is None:
        return self._out
    else:
        return ret_class(self._out)

out(panel='')

Plug the output sockets to the current tree output.

Parameters:

Name Type Description Default
panel str

panel to create the output sockets into

""
Source code in core/nodeclass.py
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
def out(self, panel: str = ""):
    """ Plug the output sockets to the current tree output.

    Parameters
    ----------
    panel : str, default=""
        panel to create the output sockets into

    """
    self.link_outputs(None, to_panel=panel)

set_input_socket(name, value, create=True, panel='', **props)

Set a value to an input socket.

If name is None (for instance when called by Socket.out()): - The first free input socket of the proper type is chosen - If not found, a socket is created when possible

Parameters:

Name Type Description Default
name Socket | str | int | None

socket name of socket index

required
value Socket or any value

value to set to the socket

required
create bool

create the value (only for node with dynamic input sockets) default=True.

True
panel str

creation panel default="".

''
props dict

additional properties (ignored)

{}

Raises:

Type Description
- AttributeError or IndexError if not found

Returns:

Type Description
The input socket
Source code in core/nodeclass.py
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
def set_input_socket(self, 
        name    : str | int, 
        value   : Any, 
        create  : bool = True, 
        panel   : str="", **props):
    """ Set a value to an input socket.

    If name is None (for instance when called by Socket.out()):
    - The first free input socket of the proper type is chosen
    - If not found, a socket is created when possible

    Parameters
    ----------
    name : Socket | str | int | None
        socket name of socket index

    value : Socket or any value
        value to set to the socket

    create : bool, optional
        create the value (only for node with dynamic input sockets) default=True.

    panel : str, optional
        creation panel default="".

    props : dict
        additional properties (ignored)


    Raises
    ------
    - AttributeError or IndexError if not found

    Returns
    -------
    The input socket
    """

    # ====================================================================================================
    # Multi input socket set with a list of value
    # ====================================================================================================

    is_multi = name in self._inputs._multi_names
    if is_multi and isinstance(value, list):
        sockets = []
        # Reversed for join strings !
        for v in reversed(value):
            sockets.append(self.set_input_socket(name, v, create=False, panel=panel))
        return sockets

    # ====================================================================================================
    # The socket is set, it can ignored in a further link_inputs
    # ====================================================================================================

    if value is not None:
        self._link_ignore.append(name)

    # ====================================================================================================
    # No value: nothing to do, otherwise let's read the socket type
    # ====================================================================================================

    # If Value is None, the type is Geometry
    # We don't exit at this stage because it could be a request to create an input socket

    value_socket_type = SocketType(value)

    # ----------------------------------------------------------------------------------------------------
    # Special naming
    # ----------------------------------------------------------------------------------------------------

    # Name can be the socket index or its identifier

    found_socket = None
    if not self._has_dyn_in and name is not None:
        if isinstance(name, int):
            found_socket = self._bnode.inputs[name]
        else:
            for s in self._bnode.inputs:
                if s.identifier == name:
                    found_socket = s
                    break

    # ----------------------------------------------------------------------------------------------------
    # Virtual socket : the input socket must exist (or auto data type)
    # ----------------------------------------------------------------------------------------------------

    if value_socket_type.is_virtual:

        auto = self._bnode.bl_idname in constants.AUTO_INPUT_TYPE_NODES
        halt = name is not None and not auto

        if name is None:
            full_name = None
        else:
            full_name = (ItemPath(panel) + name).path

        # The socket must exist
        if found_socket is None:
            in_socket = self.get_socket('INPUT', full_name, value_socket_type, free_only=True, halt=halt)
        else:
            in_socket = found_socket

        # However, if auto data type we can create it
        if in_socket is None and auto:
            in_socket = self.create_socket('INPUT', None, name=name, panel=panel, **props)

        # Error
        if in_socket is None:
            raise NodeError(
                "Impossible plug an new Input to a new Output socket.\n"
                "You tried to create a new input socket named '{name}' in node {self}. "
                "But you used the virtual socket Input which has not type. "
                "It is impossible to identify the type of socket you want to create.\n"
                f"Use Float(name='{name}') rather than Input('{name}') to create a Float socket for instance."
                )

        # Create / link the output socket
        value.node.create_from_socket('OUTPUT', in_socket, name=value.name, panel=value.panel, **value.props)

        return in_socket

    # ===========================================================================
    # Name is None: value must be a socket
    # ===========================================================================

    if name is None:
        # Specific case: index switch doesn't need a name to create a new socket
        if self._bnode.bl_idname == 'GeometryNodeIndexSwitch':
            name = str(len(self._bnode.index_switch_items) + 1)

    if name is None:

        # ----- First free input socket

        for _, socket in self.get_sockets('INPUT', free_only=True, panel=panel):

            if socket.type == value_socket_type.type:
                self._tree.link(value, socket)
                return socket

        # ----- Not found : we should be able to create it

        if not (create and self._has_dyn_in):
            raise NodeError(f"Error when setting an input socket to node {self}: no free input socket found for socket {value} of type: {value_socket_type.type}.")

        name = self.get_socket_default_name('OUTPUT', value)

    # ===========================================================================
    # Name is not None
    # ===========================================================================

    # ---------------------------------------------------------------------------
    # Get the input socket by its name
    # ---------------------------------------------------------------------------

    create_socket = create and self._has_dyn_in
    if found_socket is None:
        full_name = (ItemPath(panel) + name).path
        socket = self.get_socket('INPUT', full_name, value_socket_type, free_only=True, halt=not create_socket)
    else:
        socket = found_socket

    # ---------------------------------------------------------------------------
    # Create the dynamic socket
    # ---------------------------------------------------------------------------

    if socket is None:

        if utils.get_bsocket(value) is not None and SocketType(value) == SocketType(utils.get_bsocket(value)):
            return self.create_from_socket('INPUT', value, name=name, panel=panel, **props)

        socket_type = SocketType(value)
        socket = self.create_socket('INPUT', socket_type, name=name, panel=panel, **props)

    # ===========================================================================
    # Set a value to the socket
    # ===========================================================================

    return self.set_input_socket_value(socket, value)

set_input_socket_value(socket, value)

Set a value to an input socket

Parameters:

Name Type Description Default
socket Socket

the input socket

required
value Any

the value to set

required

Returns:

Type Description
socket
Source code in core/nodeclass.py
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
def set_input_socket_value(self, socket, value):
    """ Set a value to an input socket

    Parameters
    ----------
    socket : Socket
        the input socket

    value : Any
        the value to set


    Returns
    -------
    socket
    """

    if value is None:
        return socket

    # ---------------------------------------------------------------------------
    # We take default value from empty socket
    # ---------------------------------------------------------------------------

    if utils.is_empty_socket(value):
        value = value._bsocket

    # ---------------------------------------------------------------------------
    # If the value is a Node, we take its default output socket
    # ---------------------------------------------------------------------------

    if '_bnode' in dir(value):
        value = value._out

    # ---------------------------------------------------------------------------
    # If the value is a domain, we take its geometry
    # ---------------------------------------------------------------------------

    if '_geo' in dir(value):
        value = value._geo

    # ---------------------------------------------------------------------------
    # We directly have a socket
    # ---------------------------------------------------------------------------

    out_socket = utils.get_bsocket(value)
    if out_socket is not None:
        return self._tree.link(out_socket, socket)

    # ---------------------------------------------------------------------------
    # We need to create a node if:
    # - in_socket.hide_value is True
    # - the value is an array containing sockets : vector((0, a, 1))
    # ---------------------------------------------------------------------------

    socket_type = SocketType(socket)
    if socket.hide_value:
        self._tree.link(utils.to_socket(value)._bsocket, socket)
        return socket

    # ---------------------------------------------------------------------------
    # Setting according to the socket type
    # ---------------------------------------------------------------------------

    if socket_type.type in constants.ARRAY_TYPES:

        if not hasattr(socket, 'default_value'):
            raise NodeError(f"Impossible to set the input socket {self}.'{socket.name}' with the value: <{value}>.")

        if socket_type.type == 'RGBA':
            a = SysColor(value).rgba

        else:
            spec = constants.ARRAY_TYPES[socket_type.type]
            a = utils.value_to_array(value, spec['shape'])

        # There is a bsocket in the array
        if utils.has_bsocket(a):
            v = utils.get_socket_class(socket_type)(a)
            self._tree.link(v, socket)

        else:
            try:
                socket.default_value = list(a)
            except Exception as e:
                raise NodeError(f"Impossible to set input socket [{socket.node.name}].{socket.name} with value <{value}>. {str(e)}")

    elif socket_type.class_name in ['Boolean', 'Integer', 'Float', 'String']:
        try:
            socket.default_value = value
        except Exception as e:
            raise NodeError(f"Impossible to set input socket [{socket.node.name}].{socket.name} with value <{value}>. {str(e)}")

    elif socket.type in ['OBJECT', 'COLLECTION', 'IMAGE', 'MATERIAL']:

        bobj = blender.get_resource(socket.type, value)

        if bobj is not None:
            socket.default_value = bobj

    elif socket.type == 'FONT':
        socket.default_value = blender.get_font(value)

    elif socket.type == 'MENU':

        try:    
            socket.default_value = str(value)

        except TypeError as te:
            s = str(te)
            nfi = "not found in "
            p = s.find(nfi)
            valids = eval(s[p + len(nfi):])

            ok = False
            sval = str(value).lower()
            for itm in valids:
                if itm.lower() == sval:
                    socket.default_value = itm
                    ok = True
                    break

            if not ok:
                raise NodeError(f"Impossible to set menu [{socket.node.name}]{socket.name} with value <{value}>. {str(te)}")

        except Exception as e:
            raise NodeError(f"Impossible to set menu [{socket.node.name}]{socket.name} with value <{value}>. {str(e)}")


    else:
        raise TypeError(f"Impossible to set input socket [{socket.node.name}].{socket.name} with value <{value}>. Unsupported socket type '{socket.type}'.")


    return socket

set_parameter(name, value, halt=True)

Set a node parameter

Arguments name : str parameter name

value : any parameter value

halt : bool, optional raise an error if name is not a parameter default=True.

Returns:

Type Description
str

parameter name if properly set, None otherwise

Source code in core/nodeclass.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def set_parameter(self, name: str, value, halt: bool = True):
    """ Set a node parameter

    Arguments
    name : str
        parameter name

    value : any
        parameter value

    halt : bool, optional
        raise an error if name is not a parameter default=True.


    Returns
    -------
    str
        parameter name if properly set, None otherwise

    """
    from .constants import NODE_INFO

    node_info = NODE_INFO[self._bnode.bl_idname]
    params = node_info['params']

    param_name = name

    prop = self._bnode.bl_rna.properties.get(param_name)
    if prop is None:
        if halt:
            raise NodeError(
                f"Node {self} doesn't have a parameter named '{name}'. "
                f"Valid parameters are: {list(params.keys())}.")
        else:
            return None

    if value is None:
        return param_name

    # ---------------------------------------------------------------------------
    # Enum validation
    # ---------------------------------------------------------------------------

    # Alternate value
    alt_value = None

    if prop.type == 'ENUM':

        if param_name in ['data_type', 'input_type']:
            param_value = value
            alt_value = SocketType.get_data_type_for_node(value, self._bnode.bl_idname, param_name, on_error='HALT' if halt else 'DEFAULT')

        # Font
        elif param_name == 'font' and isinstance(value, str):
            param_value = blender.get_font(value)

        else:
            param_value = value

        if prop.is_enum_flag:

            if isinstance(param_value, str):
                param_value = set(param_value)

            values = set()
            for v in param_value:
                lvalue = v.lower()

                ok = False
                for enum_item in prop.enum_items:
                    if lvalue in (enum_item.name.lower(), enum_item.identifier.lower()):
                        values.add(enum_item.identifier)
                        ok = True
                        break

                if not ok:
                    raise NodeError(f"Value '{v}' is not valid for node parameter [{self._bnode.name}].{name}.\n"
                        f"Valid values are {[enum_item.name for enum_item in prop.enum_items]}.")

            setattr(self._bnode, param_name, values)

        else:
            lvalue = param_value.lower()

            for enum_item in prop.enum_items:
                if lvalue in (enum_item.name.lower(), enum_item.identifier.lower()):
                    setattr(self._bnode, param_name, enum_item.identifier)
                    return param_name

            if alt_value is not None:
                setattr(self._bnode, param_name, alt_value)
                return param_name

            raise NodeError(f"Value '{param_value}' is not valid for node parameter [{self._bnode.name}].{name}.\n"
                f"Valid values are {[enum_item.name for enum_item in prop.enum_items]},\n"
                f"or {[enum_item.identifier for enum_item in prop.enum_items]},"
                )

    # ---------------------------------------------------------------------------
    # Not enum
    # ---------------------------------------------------------------------------

    else:
        setattr(self._bnode, param_name, value)

    return param_name

set_signature(in_out, signature, panel='')

Set the signature .

Parameters:

Name Type Description Default
in_out 'INPUT, 'OUTPUT', 'BOTH'

input or output sockets or both

'INPUT
signature Signature

the signature to apply

required
panel str

the panel where to create the sockets default="".

''

Returns:

Type Description
dict of created sockets
Source code in core/nodeclass.py
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
def set_signature(self, 
    in_out      : Literal['INPUT', 'OUTPUT', 'BOTH'],
    signature   : Signature,
    panel       : str = ""):
    """ Set the signature .

    Parameters
    ----------
    in_out : {'INPUT, 'OUTPUT', 'BOTH'}
        input or output sockets or both

    signature : Signature
        the signature to apply

    panel : str, optional
        the panel where to create the sockets default="".


    Returns
    -------
    dict of created sockets
    """

    signature = Signature(signature)

    sigs = {}
    if in_out == 'INPUT':
        sigs['INPUT'] = signature.sockets
    elif in_out == 'OUTPUT':
        sigs['OUTPUT'] = signature.sockets
    else:
        sigs['INPUT'] = signature.inputs
        sigs['OUTPUT'] = signature.outputs

    created = {}

    for io, sockets in sigs.items():

        created[io] = {}

        for spec in sockets: #.items():
            name = spec['name']
            socket = spec.get('socket')

            if socket is None:
                stype = spec.get('bl_idname', spec.get('socket_type', 'VALUE'))
                created[io][name] = self.create_socket(io, stype, name=name, panel=panel)
            else:
                created[io][name] = self.create_from_socket(io, socket, name=name, panel=panel)

    return created

socket_by_index(in_out, index, enabled_only=True)

Get a socket by its index

Parameters:

Name Type Description Default
in_out (INPUT, OUTPUT)

input or output sockets

'INPUT'
index int

socket index

required
enabled_only bool

(bool = True) : ignore disabled sockets

True

Raises:

Type Description
- IndexError if index is incorrect

Returns:

Type Description
Socket
Source code in core/nodeclass.py
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
def socket_by_index(self, 
        in_out       : IN_OUT, 
        index        : int, 
        enabled_only : bool = True) -> Socket:
    """ Get a socket by its index

    Parameters
    ----------
    in_out : {'INPUT', 'OUTPUT'}
        input or output sockets

    index : int
        socket index

    enabled_only
        (bool = True) : ignore disabled sockets


    Raises
    ------
    - IndexError if index is incorrect

    Returns
    -------
    Socket
    """
    sockets = self.get_sockets(in_out, enabled_only=enabled_only)
    return sockets[index][1]

socket_by_name(in_out, name, socket_type, enabled_only=True, free_only=False, halt=True)

Get a socket by its name

Get a socket by its name. Valid names are: - The socket name possibly suffixed by its rank (e.g. value_1 for second socket named Value) - The python version

Parameters:

Name Type Description Default
in_out (INPUT, OUTPUT)

input or output sockets

'INPUT'
name str

socket name

required
socket_type str

socket_type

required
enabled_only bool

ignore disabled sockets default=True

True
free_only bool

ignore linked sockets default=False.

False
halt bool

raises an error if not found default=True.

True

Raises:

Type Description
- AttributeError if name not found

Returns:

Type Description
Socket
Source code in core/nodeclass.py
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def socket_by_name(self, 
        in_out       : IN_OUT, 
        name         : str, 
        socket_type  : str, 
        enabled_only : bool = True, 
        free_only    : bool = False, 
        halt         : bool = True) -> Socket:
    """ Get a socket by its name

    Get a socket by its name. Valid names are:
    - The socket name possibly suffixed by its rank (e.g. `value_1` for second socket named Value)
    - The python version

    Parameters
    ----------
    in_out : {'INPUT', 'OUTPUT'}
        input or output sockets

    name : str
        socket name

    socket_type : str
        socket_type

    enabled_only : bool
        ignore disabled sockets default=True

    free_only : bool, optional
        ignore linked sockets default=False.

    halt : bool, optional
        raises an error if not found default=True.


    Raises
    ------
    - AttributeError if name not found

    Returns
    -------
    Socket
    """

    # ====================================================================================================
    # Get from tree interface
    # ====================================================================================================

    if self._use_interface:

        intf_in_out = self._interface_in_out[in_out]
        if intf_in_out is not None:

            # All the interface socket matching the provided name
            # First With type

            isocks = self._interface.get_socket_by_python_name(
                intf_in_out, name, socket_type, parent=self._tree.get_panel(), return_all=True)

            #print("DEBUG NODE 0", name, socket_type, '-->', isocks)

            # Second without type
            if not len(isocks):
                isocks = self._interface.get_socket_by_python_name(
                    intf_in_out, name, None, parent=self._tree.get_panel(), return_all=True)

            #print("DEBUG NODE 1", name, '-->', isocks)

            # Look for the first one matching the conditions
            for isock in isocks:
                socket = self.socket_by_identifier(in_out, isock.identifier)
                bsocket = utils.get_bsocket(socket)

                if enabled_only and not bsocket.enabled:
                    continue

                if in_out == 'INPUT' and free_only and not utils.is_free(socket):
                    continue

                return socket

        if halt:
            if intf_in_out is None:
                valids = []
            else:
                valids = [s.name for s in self._interface.get_sockets(intf_in_out)]

            raise NodeError(f"Node {self} doesn't own an {intf_in_out} socket named '{name}'.\nValids are {valids}")

        return None

    # ====================================================================================================
    # No tree interface
    # ====================================================================================================

    path = ItemPath(name).ranked_long_name

    socks = self._inputs if in_out == 'INPUT' else self._outputs
    socket = socks.by_name(path)

    if socket is None:
        if halt:
            raise NodeError(f"Node {self} doesn't own an {in_out} socket named '{name}'. Valid names are {socks.names}")

    return socket