Skip to content

Node

Source code in core/nodeclass.py
 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
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 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
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 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
 831
 832
 833
 834
 835
 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
 864
 865
 866
 867
 868
 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
 973
 974
 975
 976
 977
 978
 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
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
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
1170
1171
1172
1173
1174
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
1292
1293
1294
1295
1296
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
1431
1432
1433
1434
1435
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
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
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
1794
1795
1796
1797
1798
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
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
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
1979
1980
1981
1982
1983
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
2016
2017
2018
2019
2020
2021
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
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
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
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
class Node:
    __slots__ = (
        '_tree', '_bnode', '_inputs', '_outputs',
        '_created_sockets','_geo_classes',
        '_has_dyn_in', '_has_dyn_out',
        '_has_items', '_items',
        '_use_interface', '_interface', '_interface_in_out',
        '_is_paired_input', '_is_paired_output', '_paired_input_node', '_paired_output_node',
        '_link_ignore', '_stack',
    )

    def __init__(self, node_name: str, named_sockets: dict = {}, **parameters):
        """ Node wrapper.

        A node can have dynamic sockets in two ways:
        - _has_items : with an items collection
        - _use_interface : with a NodeTree

        Attributes
        ----------
        _tree : bpy.types.NodeTree
            the tree the node belongs to

        _bnode : bpy.types.Node
            the Blender wrapped Node

        _has_dyn_in : bool
            able to create dynamic input sockets

        _has_dyn_out : bool
            able to create dynamic output sockets

        _has_items : bool
            has at least one collection of dynamic items

        _items : dict['INPUT', 'OUTPUT']
            items collections or None

        _use_interface : bool
            the node dynamic sockets are managed with a NodeTree interface

        _interface : TreeInterface
            interface of the node if it exists

        _ _interface_in_out (dict['INPUT', 'OUTPUT']) : in_out argument to access the Tree
        _is_paired_input : bool
            the node is the input node of a zone of paired nodes

        _is_paired_output : bool
            the node is the output node of a zone of paired nodes

        _paired_input_node : Node
            paired input node

        _paired_output_node : Node
            paired output node

        _default_menu : str | int
            specific to MenuSwitch and IndexSwitch, forward menu value

        - _link_ignore : ignore these sockets in link_inputs method (already set)
        - _stack : call stack for warnings

        !!! note
            NodeTree interface is used for Group Input and Output nodes and for Group node.

            - Group Node : the input sockets are interface sockets for the TreeNode
            - Group Input Node : the output sockets are input sockets of the interface
            - Group Output Node : the input sockets are output sockets of the interface

        !!! note
            The '_out' property returns the first enabled output socket

        Parameters
        ----------
        node_name : str
            Node name

        named_sockets : dict, optional
            initialization values for the node input sockets default={}.

        **parameters : dict
            node parameters and sockets
        """

        # ----------------------------------------------------------------------------------------------------
        # Initialize
        # ----------------------------------------------------------------------------------------------------

        self._stack = None

        self._tree = Tree.current_tree()

        btree = self._tree._btree
        tree_type = btree.bl_idname

        # ----------------------------------------------------------------------------------------------------
        # Create node / load existing bnode
        # ----------------------------------------------------------------------------------------------------

        create_node = isinstance(node_name, str)
        if create_node:
            bl_idname = utils.get_node_bl_idname(node_name, tree_type)

            self._bnode = btree.nodes.new(type=bl_idname)
            self._bnode.select = False
            self._tree.check_node_validity(self._bnode)

        else:
            try:
                self._bnode = node_name
            except Exception as e:
                raise NodeError(f"Impossible to initialize Node with value <{node_name}>.\n" +
                                f"'node_name' must be either a node name or an existing node.\n. {str(e)}")
            bl_idname = self._bnode.bl_idname

        self._inputs  = Sockets(self._bnode.inputs, node=self)
        self._outputs = Sockets(self._bnode.outputs, node=self)

        # ----------------------------------------------------------------------------------------------------
        # Dynamic sockets with items
        # ----------------------------------------------------------------------------------------------------

        self._created_sockets = {}
        self._geo_classes = {}

        # Able to create sockets
        self._has_dyn_in  = False
        self._has_dyn_out = False

        # Has items
        self._has_items = bl_idname in constants.ONE_ITEMS_NODES
        self._items = {'INPUT': None, 'OUTPUT': None}

        # Paired nodes
        self._is_paired_output = False
        self._is_paired_input  = False

        if self._has_items:
            items = getattr(self._bnode, constants.ONE_ITEMS_NODES[bl_idname])
            items.clear()

            found = False
            for in_out, socks in zip(('INPUT', 'OUTPUT'), (self._bnode.inputs, self._bnode.outputs)):
                for sock in socks:
                    if sock.type == 'CUSTOM':
                        found = True
                        self._items[in_out] = items
                        break
                if found:
                    break

            assert found, f"Algo error for node [{node_name}], no custom sockets for items '{constants.ONE_ITEMS_NODES[bl_idname]}'."

            self._has_dyn_in  = self._items['INPUT'] is not None
            self._has_dyn_out = self._items['OUTPUT'] is not None

        # ----------------------------------------------------------------------------------------------------
        # Parameters / sockets
        # ----------------------------------------------------------------------------------------------------

        node_info = constants.NODE_INFO[bl_idname]

        params  = {}
        sockets = {}
        for name, value in parameters.items():
            if name in node_info['params']:
                params[name] = value
            else:
                sockets[name] = value

        # Parameters first to configure the node
        self.set_parameters(**params)

        # ----------------------------------------------------------------------------------------------------
        # Dynamic sockets with NodeTree
        # ----------------------------------------------------------------------------------------------------

        self._use_interface = False

        if bl_idname == 'NodeGroupInput':

            self._use_interface = True

            self._interface = TreeInterface(self._tree._btree)
            self._interface_in_out  = {'INPUT': None, 'OUTPUT': 'INPUT'}
            self._has_dyn_out = True

        elif bl_idname == 'NodeGroupOutput':

            self._use_interface = True

            self._interface = TreeInterface(self._tree._btree)
            self._interface_in_out  = {'INPUT': 'OUTPUT', 'OUTPUT': None}
            self._has_dyn_in = True

        # ----------------------------------------------------------------------------------------------------
        # Group Node
        # Read only interface
        # ----------------------------------------------------------------------------------------------------

        elif bl_idname in ['GeometryNodeGroup', 'ShaderNodeGroup']:

            self._use_interface = True

            self._interface = TreeInterface(self._bnode.node_tree)
            self._interface_in_out  = {'INPUT': 'INPUT', 'OUTPUT': 'OUTPUT'}

        # ----------------------------------------------------------------------------------------------------
        # Node with both in / out items
        # ----------------------------------------------------------------------------------------------------

        elif bl_idname == 'NodeEvaluateClosure':
            self._has_dyn_in  = True
            self._has_dyn_out = True
            self._has_items   = True
            self._items['INPUT']  = self._bnode.input_items
            self._items['OUTPUT'] = self._bnode.output_items

        assert not (self._use_interface and self._has_items), f"Stange Node [{self._bnode.name}] with interface and items."

        # ----------------------------------------------------------------------------------------------------
        # Set the sockets
        # ----------------------------------------------------------------------------------------------------

        self._link_ignore = []

        # Menus need to set the socket before the selector

        if bl_idname == 'GeometryNodeMenuSwitch':
            menu_value = None
            for name, value in {**named_sockets, **sockets}.items():
                if name.lower() == 'menu':
                    menu_value = value
                    continue
                self.set_input_socket(name, value)

            if menu_value is not None:
                self.set_input_socket("Menu", menu_value)

        elif bl_idname == 'GeometryNodeIndexSwitch':
            index_value = None
            for name, value in {**named_sockets, **sockets}.items():
                if name.lower() == 'index':
                    index_value = value
                    continue
                self.set_input_socket(name, value)

            if index_value is not None:
                self.set_input_socket("Index", index_value)

        else:
            for name, value in {**named_sockets, **sockets}.items():
                # In specific case the socket must be ignored
                # example : Alpha socket for Shader Combine Colore
                if isinstance(name, str) and utils.snake_case(name) in constants.IGNORED_SOCKETS.get(self._bnode.bl_idname, ()):
                    continue

                self.set_input_socket(name, value)

        # ----------------------------------------------------------------------------------------------------
        # Register the node
        # ----------------------------------------------------------------------------------------------------

        self._tree.register_node(self)

    # ====================================================================================================
    # Utilities
    # ====================================================================================================

    def __str__(self):
        sname = self._bnode.label if self._bnode.label != "" else self._bnode.name
        if self._bnode.bl_idname == 'GeometryNodeGroup':
            sname += f" [{self._bnode.node_tree.name}]"
        return f"<Node '{sname}'>"

    def __repr__(self):
        s = str(self)
        s += "\nInputs\n   - "
        s += "\n   - ".join([bsock.name for bsock in self._bnode.inputs])
        s += "\nOutputs\n   - "
        s += "\n   - ".join([bsock.name for bsock in self._bnode.outputs])
        s += "\n"

        return s

    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    

    # ====================================================================================================
    # Set the node parameters
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Set one parameter
    # ----------------------------------------------------------------------------------------------------

    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')

    # ----------------------------------------------------------------------------------------------------
    # Set one parameter
    # ----------------------------------------------------------------------------------------------------

    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 several parameters
    # ----------------------------------------------------------------------------------------------------

    def set_parameters(self, **parameters):

        for param_name, param_value in parameters.items():
            self.set_parameter(param_name, param_value, halt=True)

    # ====================================================================================================
    # Accessing the sockets by their name, index or identifier
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # By identifier
    # ----------------------------------------------------------------------------------------------------

    def socket_by_identifier(self,
        in_out      : IN_OUT, 
        identifier  : str, 
        halt        : bool = True,
        ) -> Socket:
        if in_out == 'INPUT':
            for bsock in self._bnode.inputs:
                if bsock.identifier == identifier:
                    return bsock

        elif in_out == 'OUTPUT':
            for bsock in self._bnode.outputs:
                if bsock.identifier == identifier:
                    return self._to_socket(bsock)

        if halt:
            raise NodeError(f"{in_out} socket with identifier '{identifier}' not found in node '{self._bnode.name}'")

        return None

    # ----------------------------------------------------------------------------------------------------
    # List of sockets
    # ----------------------------------------------------------------------------------------------------

    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

    # ----------------------------------------------------------------------------------------------------
    # Get a socket by its index
    # ----------------------------------------------------------------------------------------------------

    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]

    # ----------------------------------------------------------------------------------------------------
    # Get a socket by its name
    # ----------------------------------------------------------------------------------------------------

    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


    # ----------------------------------------------------------------------------------------------------
    # Get a socket by something
    # ----------------------------------------------------------------------------------------------------

    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 default_name
    # ====================================================================================================

    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)

    # ====================================================================================================
    # Create a new socket from a socket 
    # ====================================================================================================

    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 a new socket
    # ====================================================================================================

    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

    # ====================================================================================================
    # Set a value to an input socket
    # ====================================================================================================

    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 an input socket
    # ====================================================================================================

    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)


    # ====================================================================================================
    # Item access
    # ====================================================================================================

    def __getitem__(self, name):
        return self.get_socket('OUTPUT', name, None)

    def __setitem__(self, name, value):
        self.set_input_socket(name, value)

    # ====================================================================================================
    # Attribute
    # ====================================================================================================

    def __getattr__(self, name):

        if name in {"__dict__", "__weakref__"}:
            raise AttributeError(name)

        try:
            return self.get_socket('OUTPUT', name, None)
        except NodeError as ne:
            raise AttributeError(str(ne))

    def __setattr__(self, name, value):
        if name in self.__slots__ or name in dir(Node):
            super().__setattr__(name, value)
            return

        self.set_input_socket(name, value)

    # ====================================================================================================
    # Returns the first enabled output socket
    # ====================================================================================================

    @property
    def _out(self) -> Socket:
        """ Returns the first enabled output socket.

        Returns
        -------
        Socket
            first enabled output socket

        """
        for bsock in self._bnode.outputs:
            if bsock.enabled and bsock.is_icon_visible and bsock.type != 'CUSTOM':
                return self._to_socket(bsock)
        return None

    # ====================================================================================================
    # Update
    # ====================================================================================================

    def _get_interface_socket(self, node_socket: bpy.types.NodeSocket):
        if not node_socket.is_linked:
            return None

        input_node = node_socket.links[0].from_node
        if input_node.bl_idname != 'NodeGroupInput':
            return

        input_socket = node_socket.links[0].from_socket
        return TreeInterface(self._tree._btree).by_identifier(input_socket.identifier)

    # ====================================================================================================
    # Wrap a Blender socket
    # ====================================================================================================

    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)

    # ====================================================================================================
    # Socket creation call back
    # ====================================================================================================

    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)

    # ====================================================================================================
    # Signature
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Get the signature
    # ----------------------------------------------------------------------------------------------------

    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)

    # ----------------------------------------------------------------------------------------------------
    # Set input signature
    # ----------------------------------------------------------------------------------------------------

    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

    # ====================================================================================================
    # Plug the node
    # ====================================================================================================

    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)

    # ====================================================================================================
    # Sockets as tuple
    # ====================================================================================================

    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')])

    # ====================================================================================================
    # Link input from another node
    # ====================================================================================================

    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 panel from another node
    # ====================================================================================================

    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


    # ====================================================================================================
    # Link input from another node
    # ====================================================================================================

    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

    # ====================================================================================================
    # Duplicate
    # ====================================================================================================

    def duplicate_node(self, links=True):

        bl_idname = self._bnode.bl_idname

        if isinstance(self, Group):
            new_node = Group(self._bnode.node_tree.name)
        else:
            new_node = Node(bl_idname)

        node_info = constants.NODE_INFO[bl_idname]
        for name in node_info['params']:
            setattr(new_node._bnode, name, getattr(self._bnode, name))

        assert len(self._bnode.inputs) == len(new_node._bnode.inputs), "Shouldn't happen !"

        for sock_from, sock_to  in zip(self._bnode.inputs, new_node._bnode.inputs):
            try:
                sock_to.default_value = sock_from.default_value
            except Exception:
                pass

            for link in sock_from.links:
                self._tree._btree.links.new(link.from_socket, sock_to)

        return new_node


    # ====================================================================================================
    # Method call
    # ====================================================================================================

    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)

    # ====================================================================================================
    # Color and label
    # ====================================================================================================

    @property
    def _color(self):
        if self._bnode.use_custom_color:
            return SysColor(self._bnode.color)
        else:
            return SysColor(None)

    @_color.setter
    def _color(self, value):

        color = Tree._get_color(value)

        if color.is_none:
            self._bnode.use_custom_color = False
        else:
            self._bnode.use_custom_color = True
            self._bnode.color = color.bcolor

    @property
    def _label(self):
        return self._bnode.label

    @_label.setter
    def _label(self, value):
        if value is None:
            return
        self._bnode.label = value

    # ====================================================================================================
    # Pin gizmo
    # The first input socket
    # ====================================================================================================

    @property
    def pin_gizmo(self):
        return self._bnode.inputs[0].pin_gizmo

    @pin_gizmo.setter
    def pin_gizmo(self, value):
        self._bnode.inputs[0].pin_gizmo = value

    # ====================================================================================================
    # Context management
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Push for capturing socket.out() and possibly zone input creation
    # ----------------------------------------------------------------------------------------------------

    def _push(self):

        # Becomes the output node
        self._tree._output_stack.append(self)

        # Becomes input node is possible
        if self._has_dyn_out:
            self._tree._input_stack.append(self)

    # ----------------------------------------------------------------------------------------------------
    # Pop capturing sockets in/out
    # ----------------------------------------------------------------------------------------------------

    def _pop(self, error: bool = False):

        assert self._tree._output_stack.pop() == self

        # Was input node
        if self._has_dyn_out:
            assert self._tree._input_stack.pop() == self

    # ----------------------------------------------------------------------------------------------------
    # Context management
    # ----------------------------------------------------------------------------------------------------

    def __enter__(self):
        self._push()
        return self

    def __exit__(self, type, exc_value, traceback):

        ok = exc_value is None or isinstance(exc_value, Break)

        self._pop(not ok)

    # ====================================================================================================
    # Class test    
    # ====================================================================================================

    @classmethod
    def _class_test(cls):

        from geonodes import GeoNodes, Node, Group, Closure, Layout, Bundle, Mesh, Vector, Boolean, Float

        group_name = "Group Demo"

        # ---------------------------------------------------------------------------
        # Group
        # ---------------------------------------------------------------------------

        with GeoNodes(group_name, is_group=True):

            # Link with two input values both named "Value"
            # Panel: Math
            node0 = Node('Math')
            node0._bnode.label = "A: From 'Add'"
            node0.link_inputs(None, "Add")

            # Link another Add node
            node1 = Node('Math')
            node1._bnode.label = "B: From A & 'Add'"
            node1.link_inputs(node0)            
            node1.link_inputs(None, "Add")
            node1.link_outputs(None, "Add")

            # A new math with "Value", "Multiplier", "Addend"
            node = Node('Math', operation='MULTIPLY_ADD')
            node._bnode.label = "C: panel 'Mul Add"
            node.link_inputs(None, "Mul Add", )
            node.link_inputs(None, "Mul Add")
            node.link_outputs(None, "Mul Add")

        # ---------------------------------------------------------------------------
        # Modifier
        # ---------------------------------------------------------------------------

        with GeoNodes("Node Class Test") as tree:

            with Layout("In/Out linked to Group", color=(.3, .1, .1)):
                node = Node('Raycast')
                node.link_inputs(None)            
                node.link_outputs(None)

            with Layout("In/Out linked to panel named \"Second\"", color=(.1, .4, .1)):                
                node = Node('Raycast')
                node.link_inputs(None, "Second")            
                node.link_outputs(None, "Second")

            with Layout("Filtering inputs and outputs sockets", color=(.1, .1, .4)):
                node = Node('Raycast')
                node.link_inputs(None, "Filtered", exclude=["Source Position", "Ray Direction"])
                node.link_outputs(None, "Filtered", include=["Hit Position"])

            with Layout("Node embedded in a closure", color=(.4, .1, .4)):
                with Closure() as cl:
                    node = Node('Raycast')
                    node.link_inputs(None, "Raycast", exclude=["Interpolation", ])
                    node.link_outputs(None, "Raycast", include=["Is Hit", "Hit Position"])

                cl.out()

            with Layout("Node feeding a Bundle", color=(.1, .4, .4)):
                with Bundle() as b:
                    node = Node('Raycast')
                    node.out()

                b.out()

            with Layout("Create Separate Bundle from a Node", color=(.1, .4, .4)):
                b = Bundle(name="Bundle")
                with b.separate():
                    node = Node('Raycast')
                    node.link_inputs(None, exclude=["Interpolation"])

            with Layout("Linking a Node Group"):
                g = Group(group_name)
                g.link_inputs(None, "Group 'Add'", panel="Add")
                g.link_outputs(None, "Group 'Mul Add'", panel="Mul Add")
                g.link_outputs(None, "Group 'Add New'", panel="Add")

                with Layout("To a Closure"):
                    with Closure() as cl:
                        g = Group(group_name)
                        g.link_inputs(None)
                        g.link_outputs(None)

                cl.out()

            with Layout("Built in Group"):
                g = Group("Curve to Tube")
                g.link_inputs(None, "Tube")
                g.link_outputs(None, "Tube")

        # ---------------------------------------------------------------------------
        # Advanced
        # ---------------------------------------------------------------------------

        class Test(Mesh):
            pass

        with GeoNodes("Advanced Translation") as tree:
            mesh = Mesh()
            t = Vector(0, "Translation")
            s = Float(1., "Scale")
            mesh.offset = t*s
            mesh.out()

        tree.add_method(Test, self_attr="self", ret_class=Test)

        with GeoNodes("New Cube") as tree:
            Mesh.Cube(size=Float(1., "Size")).out()

        tree.add_method(Test, self_attr=None, ret_class=Test)

        with GeoNodes("Group Advanced Demo"):

            test = Test.new_cube(1.)
            test = test.advanced_translation((1, 1, 1))

            test.out()

_out property

Returns the first enabled output socket.

Returns:

Type Description
Socket

first enabled output socket

__init__(node_name, named_sockets={}, **parameters)

Node wrapper.

A node can have dynamic sockets in two ways: - _has_items : with an items collection - _use_interface : with a NodeTree

Attributes:

Name Type Description
_tree NodeTree

the tree the node belongs to

_bnode Node

the Blender wrapped Node

_has_dyn_in bool

able to create dynamic input sockets

_has_dyn_out bool

able to create dynamic output sockets

_has_items bool

has at least one collection of dynamic items

_items dict[INPUT, OUTPUT]

items collections or None

_use_interface bool

the node dynamic sockets are managed with a NodeTree interface

_interface TreeInterface

interface of the node if it exists

_ _interface_in_out (dict['INPUT', 'OUTPUT']) in_out argument to access the Tree
_is_paired_input bool

the node is the input node of a zone of paired nodes

_is_paired_output bool

the node is the output node of a zone of paired nodes

_paired_input_node Node

paired input node

_paired_output_node Node

paired output node

_default_menu str | int

specific to MenuSwitch and IndexSwitch, forward menu value

- _link_ignore ignore these sockets in link_inputs method (already set)
- _stack call stack for warnings
!!! note

NodeTree interface is used for Group Input and Output nodes and for Group node.

  • Group Node : the input sockets are interface sockets for the TreeNode
  • Group Input Node : the output sockets are input sockets of the interface
  • Group Output Node : the input sockets are output sockets of the interface
!!! note

The '_out' property returns the first enabled output socket

Parameters:

Name Type Description Default
node_name str

Node name

required
named_sockets dict

initialization values for the node input sockets default={}.

{}
**parameters dict

node parameters and sockets

{}
Source code in core/nodeclass.py
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
def __init__(self, node_name: str, named_sockets: dict = {}, **parameters):
    """ Node wrapper.

    A node can have dynamic sockets in two ways:
    - _has_items : with an items collection
    - _use_interface : with a NodeTree

    Attributes
    ----------
    _tree : bpy.types.NodeTree
        the tree the node belongs to

    _bnode : bpy.types.Node
        the Blender wrapped Node

    _has_dyn_in : bool
        able to create dynamic input sockets

    _has_dyn_out : bool
        able to create dynamic output sockets

    _has_items : bool
        has at least one collection of dynamic items

    _items : dict['INPUT', 'OUTPUT']
        items collections or None

    _use_interface : bool
        the node dynamic sockets are managed with a NodeTree interface

    _interface : TreeInterface
        interface of the node if it exists

    _ _interface_in_out (dict['INPUT', 'OUTPUT']) : in_out argument to access the Tree
    _is_paired_input : bool
        the node is the input node of a zone of paired nodes

    _is_paired_output : bool
        the node is the output node of a zone of paired nodes

    _paired_input_node : Node
        paired input node

    _paired_output_node : Node
        paired output node

    _default_menu : str | int
        specific to MenuSwitch and IndexSwitch, forward menu value

    - _link_ignore : ignore these sockets in link_inputs method (already set)
    - _stack : call stack for warnings

    !!! note
        NodeTree interface is used for Group Input and Output nodes and for Group node.

        - Group Node : the input sockets are interface sockets for the TreeNode
        - Group Input Node : the output sockets are input sockets of the interface
        - Group Output Node : the input sockets are output sockets of the interface

    !!! note
        The '_out' property returns the first enabled output socket

    Parameters
    ----------
    node_name : str
        Node name

    named_sockets : dict, optional
        initialization values for the node input sockets default={}.

    **parameters : dict
        node parameters and sockets
    """

    # ----------------------------------------------------------------------------------------------------
    # Initialize
    # ----------------------------------------------------------------------------------------------------

    self._stack = None

    self._tree = Tree.current_tree()

    btree = self._tree._btree
    tree_type = btree.bl_idname

    # ----------------------------------------------------------------------------------------------------
    # Create node / load existing bnode
    # ----------------------------------------------------------------------------------------------------

    create_node = isinstance(node_name, str)
    if create_node:
        bl_idname = utils.get_node_bl_idname(node_name, tree_type)

        self._bnode = btree.nodes.new(type=bl_idname)
        self._bnode.select = False
        self._tree.check_node_validity(self._bnode)

    else:
        try:
            self._bnode = node_name
        except Exception as e:
            raise NodeError(f"Impossible to initialize Node with value <{node_name}>.\n" +
                            f"'node_name' must be either a node name or an existing node.\n. {str(e)}")
        bl_idname = self._bnode.bl_idname

    self._inputs  = Sockets(self._bnode.inputs, node=self)
    self._outputs = Sockets(self._bnode.outputs, node=self)

    # ----------------------------------------------------------------------------------------------------
    # Dynamic sockets with items
    # ----------------------------------------------------------------------------------------------------

    self._created_sockets = {}
    self._geo_classes = {}

    # Able to create sockets
    self._has_dyn_in  = False
    self._has_dyn_out = False

    # Has items
    self._has_items = bl_idname in constants.ONE_ITEMS_NODES
    self._items = {'INPUT': None, 'OUTPUT': None}

    # Paired nodes
    self._is_paired_output = False
    self._is_paired_input  = False

    if self._has_items:
        items = getattr(self._bnode, constants.ONE_ITEMS_NODES[bl_idname])
        items.clear()

        found = False
        for in_out, socks in zip(('INPUT', 'OUTPUT'), (self._bnode.inputs, self._bnode.outputs)):
            for sock in socks:
                if sock.type == 'CUSTOM':
                    found = True
                    self._items[in_out] = items
                    break
            if found:
                break

        assert found, f"Algo error for node [{node_name}], no custom sockets for items '{constants.ONE_ITEMS_NODES[bl_idname]}'."

        self._has_dyn_in  = self._items['INPUT'] is not None
        self._has_dyn_out = self._items['OUTPUT'] is not None

    # ----------------------------------------------------------------------------------------------------
    # Parameters / sockets
    # ----------------------------------------------------------------------------------------------------

    node_info = constants.NODE_INFO[bl_idname]

    params  = {}
    sockets = {}
    for name, value in parameters.items():
        if name in node_info['params']:
            params[name] = value
        else:
            sockets[name] = value

    # Parameters first to configure the node
    self.set_parameters(**params)

    # ----------------------------------------------------------------------------------------------------
    # Dynamic sockets with NodeTree
    # ----------------------------------------------------------------------------------------------------

    self._use_interface = False

    if bl_idname == 'NodeGroupInput':

        self._use_interface = True

        self._interface = TreeInterface(self._tree._btree)
        self._interface_in_out  = {'INPUT': None, 'OUTPUT': 'INPUT'}
        self._has_dyn_out = True

    elif bl_idname == 'NodeGroupOutput':

        self._use_interface = True

        self._interface = TreeInterface(self._tree._btree)
        self._interface_in_out  = {'INPUT': 'OUTPUT', 'OUTPUT': None}
        self._has_dyn_in = True

    # ----------------------------------------------------------------------------------------------------
    # Group Node
    # Read only interface
    # ----------------------------------------------------------------------------------------------------

    elif bl_idname in ['GeometryNodeGroup', 'ShaderNodeGroup']:

        self._use_interface = True

        self._interface = TreeInterface(self._bnode.node_tree)
        self._interface_in_out  = {'INPUT': 'INPUT', 'OUTPUT': 'OUTPUT'}

    # ----------------------------------------------------------------------------------------------------
    # Node with both in / out items
    # ----------------------------------------------------------------------------------------------------

    elif bl_idname == 'NodeEvaluateClosure':
        self._has_dyn_in  = True
        self._has_dyn_out = True
        self._has_items   = True
        self._items['INPUT']  = self._bnode.input_items
        self._items['OUTPUT'] = self._bnode.output_items

    assert not (self._use_interface and self._has_items), f"Stange Node [{self._bnode.name}] with interface and items."

    # ----------------------------------------------------------------------------------------------------
    # Set the sockets
    # ----------------------------------------------------------------------------------------------------

    self._link_ignore = []

    # Menus need to set the socket before the selector

    if bl_idname == 'GeometryNodeMenuSwitch':
        menu_value = None
        for name, value in {**named_sockets, **sockets}.items():
            if name.lower() == 'menu':
                menu_value = value
                continue
            self.set_input_socket(name, value)

        if menu_value is not None:
            self.set_input_socket("Menu", menu_value)

    elif bl_idname == 'GeometryNodeIndexSwitch':
        index_value = None
        for name, value in {**named_sockets, **sockets}.items():
            if name.lower() == 'index':
                index_value = value
                continue
            self.set_input_socket(name, value)

        if index_value is not None:
            self.set_input_socket("Index", index_value)

    else:
        for name, value in {**named_sockets, **sockets}.items():
            # In specific case the socket must be ignored
            # example : Alpha socket for Shader Combine Colore
            if isinstance(name, str) and utils.snake_case(name) in constants.IGNORED_SOCKETS.get(self._bnode.bl_idname, ()):
                continue

            self.set_input_socket(name, value)

    # ----------------------------------------------------------------------------------------------------
    # Register the node
    # ----------------------------------------------------------------------------------------------------

    self._tree.register_node(self)

_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)

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