Skip to content

Socket

Bases: NodeCache

The output socket of a Node

Socket is the base class for data classes such as Float, Image or Geometry.

It refers to an output socket of a Node. A socket can be set to the input socket of another Node to create a link between the two nodes:

# cube is the output socket 'Mesh' of the node 'Cube'
cube = Node("Cube").mesh

# cube is set the to socket 'geometry' of node 'Set Position'
node = Node("Set Position")
node.geometry = cube

Important

You can access to the other output sockets of the node in two different ways:

  • using node attribute
  • using *peer socket naming convention where the snake_case name of the other sockets is suffixed by '_'

The example below shows how to access the to 'UV Map' socket of node <*Node Cube>:

# cube is the output socket 'Mesh' of the node 'Cube'
cube = Mesh.Cube()

# Getting 'UV Map' through the node
uv_map = cube.node.uv_map

# Or using the 'peer socket' naming convention
uv_map = cuve.uv_map_
Source code in core/socket_class.py
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 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
class Socket(NodeCache):
    """ > The output socket of a Node

    **Socket** is the base class for data classes such as Float, Image or Geometry.

    It refers to an **output** socket of a Node. A socket can be set to the **input** socket
    of another Node to create a link between the two nodes:

    ``` python
    # cube is the output socket 'Mesh' of the node 'Cube'
    cube = Node("Cube").mesh

    # cube is set the to socket 'geometry' of node 'Set Position'
    node = Node("Set Position")
    node.geometry = cube
    ```

    !!! important
        You can access to the other output sockets of the node in two different ways:

        - using node attribute
        - using ***peer socket** naming convention where the **snake_case** name of the other sockets is suffixed by '_'

    The example below shows how to access the to 'UV Map' socket of node <*Node Cube>:

    ``` python
    # cube is the output socket 'Mesh' of the node 'Cube'
    cube = Mesh.Cube()

    # Getting 'UV Map' through the node
    uv_map = cube.node.uv_map

    # Or using the 'peer socket' naming convention
    uv_map = cuve.uv_map_
    ```
    """    

    __slots__ = NodeCache.__slots__ + ('_tree', '_bsocket', '_layout', '_use_layout')

    SOCKET_TYPE = None

    # ====================================================================================================
    # Initialization
    # ====================================================================================================

    def __init__(self, 
            socket  = None, 
            name         : str = None, 
            tip          : str = "",
            panel        : str = "",
            user_label   : str = None,
            **props):
        """

        Parameters
        ----------
        socket : NodeSocket, optional
            the output socket to wrap default=None.

        name : str, optional
            input name if not None default=None.

        tip : str, optional
            description default="".

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

        user_label : str, optional
            user label default=None.

        """

        # ---------------------------------------------------------------------------
        # Attributes
        # ---------------------------------------------------------------------------

        self._layout      = None
        self._use_layout  = True
        self._tree        = Tree.current_tree()
        if self._tree is not None and not self._tree._rebuild:
            raise Break()
        self._bsocket     = None

        self._reset()

        # ---------------------------------------------------------------------------
        # Socket is a Node
        # ---------------------------------------------------------------------------

        if isinstance(socket, Node):
            socket = socket._out

        # ---------------------------------------------------------------------------
        # Empty socket
        # ---------------------------------------------------------------------------

        if utils.request_empty(socket):
            return

        # ---------------------------------------------------------------------------
        # Socket is a string or a String socket
        # ---------------------------------------------------------------------------

        socktype = self._socket_type
        cname = socktype.class_name

        if socktype.is_attribute:
            # Literal color names remain constants; String sockets name attributes.
            if ((isinstance(socket, str) and cname != 'Color') or
                    (isinstance(socket, Socket) and socket.SOCKET_TYPE == 'STRING')):
                self._bsocket = self.Named(socket)._bsocket
                return

        # ---------------------------------------------------------------------------
        # Let's get the socket
        # ---------------------------------------------------------------------------

        self._bsocket = utils.get_bsocket(socket)
        if self._bsocket is not None:

            if self._bsocket.type != self.SOCKET_TYPE:

                # "Bundle Get Item" like nodes : we change the data_type
                node = self.node

                blid = node._bnode.bl_idname
                if blid == 'NodeGetBundleItem'and self.SOCKET_TYPE in utils.get_node_param_enum(blid, 'socket_type'):
                    node._bnode.socket_type = self.SOCKET_TYPE
                    self._bsocket = utils.get_enabled_bsocket(node, 'Item')

            return

        # ---------------------------------------------------------------------------
        # No name: we create from a constant Node
        # The socket argument is the value to set
        # ---------------------------------------------------------------------------

        if name is None:
            if socktype == 'GEOMETRY':
                new_socket = self.Input(None, halt=False)
                if new_socket is None:
                    new_socket = self.NewInput(type(self).__name__)
                self._bsocket = new_socket._bsocket
            else:
                self._bsocket = self.Constant(socket, user_label=user_label)._bsocket

        # ---------------------------------------------------------------------------
        # With a name, we request the creation from current input
        # ---------------------------------------------------------------------------

        else:
            # Font : make sure it is a font 
            if self.SOCKET_TYPE == 'FONT':
                socket = blender.get_font(socket)

            # Socket can be the default value
            if socket is not None:

                if 'default' not in constants.SOCKETS[self._socket_type.type]['props']:
                    raise NodeError(f"The {self._socket_type()} socket doesn't accept default value. <{socket}> is not valid.")

                # Perhaps it is given in the props
                def_key = 'default' if 'default' in props else None
                if def_key is None:
                    def_key = 'default_value' if 'default_value' in props else None

                if def_key is None:
                    props = {'value': socket, **props}

            new_socket = self.NewInput(name, tip=tip, panel=panel, **props)
            self._bsocket = new_socket._bsocket
            self._use_layout = new_socket._use_layout

    # ====================================================================================================
    # Constructors
    # ====================================================================================================

    def _convert_to_class(self, class_name):
        from .utils import SOCKET_CLASSES, GEOMETRY_CLASSES

        classes = {
            cls.__name__: cls
            for cls in SOCKET_CLASSES.values()
        } | GEOMETRY_CLASSES

        try:
            cls = classes[class_name]
        except KeyError:
            raise NodeError(f"Unknown Socket class {class_name!r}") from None

        return cls(self)

    # ----------------------------------------------------------------------------------------------------
    # An empty socket
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def Empty(cls, value = None):
        """ Create an empty socket.

        An empty socket is used temporarily as an input for nodes with dynamic sockets:

        Parameters
        ----------
        value : Any, optional
            default value default=None.

        """
        socket = cls(constants.EMPTY_SOCKET)
        socket._bsocket = SocketType.from_type(cls.SOCKET_TYPE).get_default_from_value(value)
        return socket

    # ----------------------------------------------------------------------------------------------------
    # Named attribute
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def Named(cls, name):
        """ > Node Named Attribute

        Information
        -----------
        - Parameter 'data_type' : 'BOOLEAN'

        Parameters
        ----------
        name : String
            socket 'Name' (id: Name)


        Returns
        -------
        Boolean
        """
        if SocketType.from_type(cls.SOCKET_TYPE).class_name not in constants.ATTRIBUTE_CLASSES:
            raise NodeError(
                f"The class {SocketType.from_type(cls.SOCKET_TYPE).class_name} is not an attribute.\n"
                f"Attribute classes are: {constants.ATTRIBUTE_CLASSES}")

        node = Node('Named Attribute', name=name)
        data_type = SocketType.from_type(cls.SOCKET_TYPE).get_node_data_type(
            tree_type = node._tree._btree.bl_idname,
            bl_idname = node._bnode.bl_idname,
            halt = True)

        node.set_parameter('data_type', data_type)

        return node._out._ul(name)

    # ----------------------------------------------------------------------------------------------------
    # An existing group input socket (output socket of input node)
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def Input(cls, name: str, panel: str = "", halt: bool = True):
        """ Get an exist input socket from its name and panel.

        !!! note
            The "input" socket here is an "output" socket of the current input node

        To create a input socket use NewInput.

        If the 'name' argument is None, the first socket of the proper type is returned.

        Raises
        ------
        - NodeError if socket is not found and halt is requested

        Parameters
        ----------
        name : str | None
            socket name

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

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


        Returns
        -------
        Socket
        """
        in_node = Tree.current_tree().get_input_node()

        include = None if name is None else [name]
        bsockets = in_node.get_sockets('OUTPUT', include=include, panel=panel)

        for _, bsock in bsockets:
            if SocketType(bsock).type == cls.SOCKET_TYPE: # and utils.snake_case(sock_name) == utils.snake_case(name):
                return cls(bsock._bsocket)._ul(name)

        if halt:
            sname = "" if name is None else f" named '{name}'"
            raise NodeError(
                f"There is no {SocketType.from_type(cls.SOCKET_TYPE).class_name} input socket{sname}.\n"
                f"Available sockets are : {[bsock[0] for bsock in in_node.get_sockets('OUTPUT')]}.")

        return None

    # ----------------------------------------------------------------------------------------------------
    # Create a new input socket from the current I/O context
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def NewInput(cls,
            name: str, 
            value       = None, 
            tip: str    = "", 
            panel: str  = "", 
            **props):
        """ Create an new input socket

        !!! note
            The "input" socket here is an "output" socket of the current input node

        To get an existing input socket use Input.

        Raises
        ------
        - NodeError if socket is not found

        Parameters
        ----------
        name : str
            socket name

        value : Any, optional
            default_value default=None.

        tip : str, optional
            description default="".

        panel : str: None
            panel name


        Returns
        -------
        Socket
        """
        if value is None:
            defval = None
        else:
            defval = SocketType.from_type(cls.SOCKET_TYPE).get_default_from_value(value)
            new_props = {**props}

            if 'default' in new_props:
                new_props['default'] = defval

            elif 'default_value' in new_props:
                new_props['default_value'] = defval

            else:
                if 'default' not in constants.SOCKETS[cls.SOCKET_TYPE]['props']:
                    raise NodeError(f"The {SocketType.from_type(cls.SOCKET_TYPE).class_name} socket doesn't accept a default value. Value argument <{value}> is invalid.")

                new_props['default_value'] = defval

            props = new_props

        return cls(Tree.current_tree().create_input_socket(
            SocketType.from_type(cls.SOCKET_TYPE).socket_id,
            name         = name,
            tip          = tip,
            panel        = panel,
            **props))

    # ----------------------------------------------------------------------------------------------------
    # Create a socket from a constant Node
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def Constant(cls, value: None, user_label: str = ""):
        """ Create an input socket from a constant Node.

        Parameters
        ----------
        value : Any, optional
            constant default value default=None.

        user_label : str, optional
            socket name (used to rename nodes if not None) default="".
        """

        # ---------------------------------------------------------------------------
        # Ensure array
        # ---------------------------------------------------------------------------

        def get_shaped(v, *shapes):
            r = np.ravel(v)
            shape = np.shape(r)
            if shape in shapes:
                return tuple(r)

            if shape == (1,):
                return tuple(np.resize(r, shapes[0]))

            raise NodeError(
                f"The value <{v}> can't be transformed in a valid initial value for {SocketType.from_type(cls.SOCKET_TYPE).class_name}."
            )

        # ---------------------------------------------------------------------------
        # Does the array contain sockets
        # ---------------------------------------------------------------------------

        def has_sockets(a):
            for v in a:
                if SocketType.get_bsocket(v) is not None:
                    return True
            return False

        # ---------------------------------------------------------------------------
        # Default value
        # ---------------------------------------------------------------------------

        socket_type = SocketType.from_type(cls.SOCKET_TYPE)
        if cls.SOCKET_TYPE not in ['RGBA', 'VECTOR', 'ROTATION', 'MATRIX']:
            def_val = socket_type.get_default_from_value(value)

        # ---------------------------------------------------------------------------
        # Depending on the socket type
        # ---------------------------------------------------------------------------

        if cls.SOCKET_TYPE == 'BOOLEAN':
            return Node('Boolean', boolean=def_val)._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'BUNDLE':
            return Node("Combine Bundle")._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'CLOSURE':
            socket = ZoneNode.Closure().closure
            socket._use_layout = False
            return socket._ul(user_label)

        elif cls.SOCKET_TYPE == 'COLLECTION':
            return Node('Collection', collection=def_val)._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'RGBA':

            if value is None:
                a = (0, 0, 0, 1)
            elif isinstance(value, str):
                #a = colors.to_color(value)
                a = SysColor(value).rgba
            else:
                a = get_shaped(value, (4,), (3,))

            if has_sockets(a):
                if Tree.is_geonodes():
                    node = Node('Combine Color', {0: a[0], 1: a[1], 2:a[2]})
                    if len(a) == 4:
                        node.alpha = a[3]
                    return node._out._ul(user_label)
                else:
                    return Node('Combine Color', {0: a[0], 1: a[1], 2:a[2]})._out._ul(user_label)

            else:
                def_val = SocketType.from_type('COLOR').get_default_from_value(a)
                if Tree.is_geonodes():
                    return Node('Color', value=def_val)._out._ul(user_label)

                else:
                    socket = Node('Color')._out
                    socket._bsocket.default_value = def_val
                    return socket._ul(user_label)

        elif cls.SOCKET_TYPE == 'IMAGE':
            return Node('Image', image=def_val)._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'INT':
            return Node('Integer', integer=def_val)._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'MATERIAL':
            return Node('Material', material=def_val)._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'MATRIX':

            if value is None:
                a = (1, 0, 0, 0,   0, 1, 0, 0,   0, 0, 1, 0,   0, 0, 0, 1)
            else:
                a = get_shaped(value, (16,))

            return Node('Combine Matrix', named_sockets = {i: a[i] for i in range(16)})._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'MENU':
            if True: # V5.2
                from .generated.static_nd import ND
                return ND.menu(value)
                #return Node('Menu', value=value)._out._ul(user_label)
            else:
                return Node('Menu Switch')._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'OBJECT':
            return Node('Object', object=def_val)._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'FONT':
            if True: # V5.2
                return Node('Font', font=def_val)._out._ul(user_label)
            else:
                return cls.NewInput("Font", value)

        elif cls.SOCKET_TYPE == 'ROTATION':

            if value is None:
                a = (0, 0, 0)
            else:
                a = get_shaped(value, (3,))

            if has_sockets(a):
                return Node('Combine XYZ', x=a[0], y=a[1], z=a[2])._out.to_rotation()._ul(user_label)
            else:
                return Node('Rotation', rotation_euler=a)._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'STRING':
            return Node('String', string=def_val)._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'VALUE':
            node = Node('Value')
            node._bnode.outputs[0].default_value = def_val
            return node._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'VECTOR':

            if value is None:
                a = (0, 0, 0)
            else:
                a = get_shaped(value, (3,))

            if has_sockets(a):
                return Node('Combine XYZ', x=a[0], y=a[1], z=a[2])._out._ul(user_label)
            else:
                return Node('Vector', vector=a)._out._ul(user_label)

        elif cls.SOCKET_TYPE == 'GEOMETRY':
            raise NodeError(f"There is no node to create a Geometry. Use explicit constructors such as 'Mesh.Cube()', 'Curve.Spiral()' or 'Cloud.Points().")

        else:
            assert False, f"Shouldn't happen {socket_type}"

    # ----------------------------------------------------------------------------------------------------
    # Create a List from a list
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def List(cls, *items, name: str = ""):
        """ Create a Blender List from items.

        Parameters
        ----------
        items : Any, optional
            Items to put in the list.

        name : str, optional
            socket name  default="".

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

        from .sock_closure import Closure
        from .sock_integer import Integer

        with Closure() as cl:

            idx = Integer(0, "Index")

            if True:
                value = cls.IndexSwitch(*items, index=idx)
            else:
                with cls.IndexSwitch(index=idx) as value:
                    for item in items:
                        cls(item).out()

            if name == "":
                name = cls.__name__
            value.out(name)

        return cls(cl.to_list(count=len(items)))


    # ====================================================================================================
    # Emptyness
    # ====================================================================================================

    def _is_empty(self, halt_message: str = None):
        if isinstance(self._bsocket, bpy.types.NodeSocket):
            return False

        if halt_message is None:
            return True
        else:
            raise NodeError(f"Empty socket error:\n{halt_message}")

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

    @property
    def _socket_type(self):
        return SocketType.from_type(self.SOCKET_TYPE)

    def __str__(self):
        if self._is_empty():
            return f"<{self._socket_type.class_name}: Empty>"
        else:
            bnode = self._bsocket.node
            index = None
            for i, bsock in enumerate(bnode.outputs):
                if bsock == self._bsocket:
                    index = i
                    break

            return f"<{type(self).__name__}: [{self.node._bnode.name}][{index}].'{self._bsocket.name}'>"

    def _reset(self):
        self._cache_reset()

    # ----------------------------------------------------------------------------------------------------
    # Jump to another output socket
    # ----------------------------------------------------------------------------------------------------

    def _jump(self, socket: bpy.types.NodeSocket, reset: bool = True):
        """ Change the wrapped output socket

        When changing the socket, the description is copied to the new socket.
        The node color, if any, is also propagated.

        Parameters
        ----------
        socket : bpy.types.NodeSocket
            the new output socket to jump to

        reset : bool, optional
            reset the cache default=True.


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

        # Keep user label stored in socket description
        user_label = self.user_label

        bsocket = utils.get_bsocket(socket)
        if bsocket is None:
            raise NodeError(f"Socket error: Impossible to jump to socket {socket}")

        self._bsocket = bsocket
        if reset:
            self._reset()

        # Restore user label
        self.user_label = user_label

        return self

    # ----------------------------------------------------------------------------------------------------
    # Geometry from domain
    # ----------------------------------------------------------------------------------------------------

    @property
    def _domain_to_geometry(self):
        return self

    # ----------------------------------------------------------------------------------------------------
    # Get the interface socket (for Group node or tree input / output)
    # ----------------------------------------------------------------------------------------------------

    @property
    def _interface_socket(self):
        """ Return the interface socket if exists

        An interface socket exists when the socket a tree input or output socket or
        when it is the socket of a group

        Returns
        -------
        Interface Socket
        """
        if self.node._use_interface:
            return self.node._interface.by_identifier(self._bsocket.identifier)

        return None

    # ----------------------------------------------------------------------------------------------------
    # Name or label
    # ----------------------------------------------------------------------------------------------------

    @property
    def node(self):

        self._is_empty(f"Impossible to get the node of an empty socket '{type(self).__name__}'.")

        # Not yet initialized
        if not hasattr(self, '_bsocket'):
            return None

        return self._tree._nodes[self._bsocket.node.name]

    # ----------------------------------------------------------------------------------------------------
    # Name or label
    # ----------------------------------------------------------------------------------------------------

    @property
    def _name(self):
        """ Return the name or the label

        Returns
        -------
        str
            default is ""

        """
        if self._is_empty():
            return "<EMPTY SOCKET>"

        if self.node_label in [None, ""]:
            return utils.get_socket_name(self._bsocket)
        else:
            return self.node_label


    # ----------------------------------------------------------------------------------------------------
    # Get the panel name
    # ----------------------------------------------------------------------------------------------------

    @property
    def _panel_name(self):
        """ Return the name of the panel

        Returns
        -------
        str
            default is ""

        """
        i_socket = self._interface_socket
        if i_socket is None:
            return ""

        names = []
        cur = i_socket
        while True:
            if cur.parent.name == "":
                break
            names.append(cur.parent.name)
            cur = cur.parent

        return " > ".join(reversed(names))

    # ====================================================================================================
    # Default value property
    # ====================================================================================================

    @property
    def default_value(self):
        if not hasattr(self._bsocket, 'default_value'):
            raise NodeError(f"Socket {self} has not default value.")

        return self._bsocket.default_value

    @default_value.setter
    def default_value(self, value):
        if not hasattr(self._bsocket, 'default_value'):
            raise NodeError(f"Socket {self} has not default value.")

        self._bsocket.default_value = value

        # ----- Interface
        i_socket = self._interface_socket
        if i_socket is not None:
            i_socket.default_value = value

    # ====================================================================================================
    # Getting the socket from nodes
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Get an existing socket from current input node
    # Contrarilty to Input, doesn't raise an error
    # ----------------------------------------------------------------------------------------------------

    def _get_bsocket_from_input(self, name: str = None) -> bpy.types.NodeSocket:
        """ Get the availble input socket if any.

        The socket is get a an OUTPUT socket of the current input.

        Parameters
        ----------
        name : str, optional
            name filter default=None.


        Returns
        -------
        Socket
            or None if not found

        """
        in_node = self._tree.get_input_node()

        include = None if name is None else [name]

        bsockets = in_node.get_sockets('OUTPUT', include=include)
        for _, bsock in bsockets:
            if SocketType(bsock).type == self.SOCKET_TYPE:
                return bsock._bsocket
        else:
            return None

    # ====================================================================================================
    # Grid
    # ====================================================================================================

    @property
    def is_grid(self):
        """ bool property

        Returns True if socket is a grid (inferred_structure_type == 'GRID').
        """
        if self._is_empty():
            return False
        return self._bsocket.inferred_structure_type == 'GRID'

    # ====================================================================================================
    # List
    # ====================================================================================================

    @property
    def _is_list(self):
        """ bool property

        Returns True if socket is a list
        """
        if self._is_empty():
            return False
        return self._bsocket.inferred_structure_type == 'LIST'

    def __getitem__(self, index):
        return self.get_list_item(index)

    @property
    def len(self):
        """ Short cut for 'self.list_length()'
        """
        return self.list_length()

    def field_to_list(self, count, **values):
        """ > Node Field to List

        Create a list from this field and named lists from additional fields.

        Parameters
        ----------
        count : Integer
            Number of items in each generated list.

        values : dict
            Named fields to evaluate. Each field creates an output socket with
            the same name.

        Returns
        -------
        Socket
            First list output. The other outputs are available from its node
            or as peer sockets.
        """
        return Node(
            'Field to List',
            named_sockets={self._name: self},
            count=count,
            **values,
        )._out

    def to_list(self, count=None):
        """ > Node Field to List

        Shortcut for ``self.field_to_list(count)`` when only this field has
        to be converted to a list.

        Parameters
        ----------
        count : Integer, optional
            Number of items in the generated list.

        Returns
        -------
        Socket
            List containing the values obtained by evaluating this field.
        """
        return Node('Field to List', named_sockets={self._name: self}, count=count)._out

    def list_append(self, value):
        """Append a value or another list to this list.

        If ``value`` is a list socket, all its items are appended. Otherwise,
        ``value`` is converted to the socket type and appended as one item.
        The socket is updated in place to point to the resulting list.

        ``` python
        values = Float.List(1, 2, 3)
        values.list_append(4)

        other = Float.List(5, 6)
        values.list_append(other)
        ```

        Parameters
        ----------
        value : Any | Socket
            Single value or list socket to append.

        Returns
        -------
        Socket
            This socket, updated to point to the concatenated list.

        Raises
        ------
        NodeError
            If this socket does not contain a list.
        """

        from .sock_closure import Closure
        from .sock_integer import Integer

        if not self._is_list:
            raise NodeError(f"Socket.list_append error: {self} is not a list.")

        with Layout("Socket.list_append"):

            # Turn the appended value into a closure indexed from zero.
            in_cl = None
            if isinstance(value, Socket) and value._is_list:
                n = value.list_length()
                with Closure() as cl:
                    index = Integer(0, "Index")
                    value[index].out("Value")
                in_cl = cl
            else:
                n = 1
                with Closure() as cl:
                    index = Integer(0, "Index")
                    type(self)(value).out("Value")
                    index.out() # To avoid warning
                in_cl = cl

            cur_length = self.list_length()

            # Keep the current items first, then evaluate the appended value.
            with Closure() as cl:
                index = Integer(0, "Index")

                v = type(self).Switch(index.less_than(cur_length), 
                        in_cl.evaluate(index=index-cur_length).value,
                        self[index]
                        )
                v.out(self._name)

            # Replace the wrapped socket while preserving its Python identity.
            return self._jump(cl.to_list(cur_length + n))

    def flatten_list(self):
        """Flatten one level of a rectangular nested list.

        Every nested list must have the same length. This is notably the case
        for lists created by :meth:`reshape_list`. Items keep their original
        linear order.

        ``` python
        values = Float.List(*range(16))
        values.reshape_list((4, 4))
        values.flatten_list()
        ```

        Returns
        -------
        Socket
            This socket, updated to point to the flattened list.

        Raises
        ------
        NodeError
            If this socket does not contain a list.
        """

        if not self._is_list:
            raise NodeError(f"Socket.flatten_list error: {self} is not a list.")

        from .sock_closure import Closure
        from .sock_integer import Integer

        with Layout("Socket.flatten_list"):

            source = self
            outer_length = source.list_length()
            inner_length = source[0].list_length()

            with Closure() as cl:
                index = Integer(0, "Index")

                outer_index = index // inner_length
                inner_index = index % inner_length

                source[outer_index][inner_index].out(self._name)

            self._jump(cl.to_list(outer_length * inner_length))
            return self



    def reshape_list(self, shape):
        """Reshape a flat list into nested lists.

        ``shape`` defines the length of each list level. Items keep their
        original linear order.

        ``` python
        values = Float.List(*range(16))
        matrix = values.reshape_list((4, 4))

        first  = matrix[0][0]
        last   = matrix[3][3]
        ```

        Shapes with more than two dimensions are supported:

        ``` python
        values = Float.List(*range(24))
        blocks = values.reshape_list((2, 3, 4))
        ```

        Dimensions can also be Integer sockets:

        ``` python
        rows = Integer(name="Rows")
        table = values.reshape_list((rows, 4))
        ```

        A single dimension does not require a tuple:

        ``` python
        values.reshape_list(16)
        # Equivalent to values.reshape_list((16,))
        ```

        A one-dimensional shape flattens one existing level of nested lists.
        A warning is emitted when the resulting length differs from the
        requested dimension.

        Parameters
        ----------
        shape : int | Integer | tuple[int | Integer]
            Length of every dimension. A single integer is interpreted as a
            one-dimensional shape. Dimensions must be strictly positive.

        Returns
        -------
        Socket
            This socket, updated to point to the reshaped list.

        """

        if not hasattr(shape, '__len__'):
            shape = (shape,)

        shape = tuple(shape)

        ok_shape = True
        for d in shape:
            if isinstance(d, Socket):
                oK_shape = False

        shape_str = f"({shape})" if ok_shape else ""

        from .sock_closure import Closure
        from .sock_integer import Integer
        from .sock_string import String

        with Layout(f"Socket.reshape_list{shape_str}"):

            if len(shape) == 1:

                self.flatten_list()

                res_length = self.list_length()

                message = String.Join(
                    f"{self._name}.reshape_list(" + Integer(shape[0]).to_string() + ")",
                    "the resulting list length is",
                    res_length.to_string(),
                    delimiter = " ",
                )

                self.list_length().not_equal(shape[0]).warning(message)
                return self

            dimensions = [Integer(size) for size in shape]

            # ----- Build nested lists

            def build(level, linear_index=None):
                with Closure() as closure:
                    index = Integer(0, "Index")

                    if linear_index is None:
                        next_index = index
                    else:
                        next_index = linear_index * dimensions[level] + index

                    if level == len(dimensions) - 1:
                        value = self[next_index]
                    else:
                        value = build(level + 1, next_index)

                    value.out("Value")

                return closure.to_list(count=dimensions[level])

            self._jump(build(0))
            return self

    def to_node_inputs(self, node, *names):
        """Connect successive list items to a node's inputs.

        This is the natural socket-oriented shortcut for
        ``node._list_to_inputs(*names, socket_list=self)``.

        When ``names`` is empty, all node inputs matching the type of the list
        items are fed, in their order on the node. Otherwise, only the named
        inputs are used.

        ``` python
        separate = Node('Separate XYZ', vector=vector)
        components = separate._outputs_to_list()

        combine = Node('Combine XYZ')
        components.to_node_inputs(combine)
        ```

        Parameters
        ----------
        node : Node
            Node whose inputs are to be connected.

        names : str
            Optional names of the inputs to feed.

        Returns
        -------
        Node
            The target node.
        """
        return node._list_to_inputs(*names, socket_list=self)

    # ====================================================================================================
    # Owning node
    # ====================================================================================================

    @property
    def node_color(self):
        """ Node color

        Returns
        -------
        SysColor
        """
        return self.node._color

    @node_color.setter
    def node_color(self, value):
        self.node._color = value

    @property
    def node_label(self):
        """ Node Label

        Returns
        -------
        str
        """
        return self.node._label

    @node_label.setter
    def node_label(self, value):
        self.node._label = value

    # ----------------------------------------------------------------------------------------------------
    # Socket description is used as user label
    # treearrange will have access to this description to properly name the reroute nodes
    # ----------------------------------------------------------------------------------------------------

    @property
    def user_label(self):
        if self.node._bnode.bl_idname == 'NodeGroupInput':
            return self._bsocket.name

        d = self._bsocket.description
        if d.startswith("UL "):
            return d[3:]
        else:
            return ""

    @user_label.setter
    def user_label(self, value):
        if self.node._bnode.bl_idname == 'NodeGroupInput':
            return

        if value is None:
            return

        self._bsocket.description = "UL " + str(value)

    # ----------------------------------------------------------------------------------------------------
    # Set user label and returns self for chaining
    # ----------------------------------------------------------------------------------------------------

    def _ul(self, label : str):
        """ Set the user label

        Parameters
        ----------
        label : str
            the label to append


        Returns
        -------
        self
        """
        self.user_label = label
        return self

    # ----------------------------------------------------------------------------------------------------
    # Set Node color and label plus socket description 
    # ----------------------------------------------------------------------------------------------------

    def _lc(self, label: str = None, color: SysColor = None):
        """ Set node label and color.

        This method returns self to be chained to as socket:

        ``` python
        with GeoNodes("Node label and color"):
            Geometry().out()

            a = Float(10)._lc("Var a")
            b = Float(10)._lc("Var b")
            c = (a + b)._lc("a + b", (1, 0, 0))
        ```

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

        color : SysColor, optional
            node color default=None.


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

        if self.node._bnode.bl_idname == 'NodeGroupInput':
            return self

        self.node_label = label
        self.node_color = color
        self.user_label = label

        return self

    def _lcop(self, label=None):
        return self._lc(label=label, color='OPERATION')

    # =============================================================================================================================
    # Link node from
    # =============================================================================================================================

    def link_inputs(self,
        from_node   : Node = None,
        from_panel  : str = "",
        *,
        include     : list =  None,
        exclude     : list  = [],
        panel       : str = "",
        ):
        """ Link input sockets of the node

        Allow to chain input sockets linking.
        """
        self.node.link_inputs(from_node, from_panel=from_panel, include=include, exclude=exclude, panel=panel)
        return self

    def link_panel(self, panel: str, from_node : Node = None):
        """ Link panel input sockets of the node

        Allow to chain input sockets linking.
        """
        self.node.link_panel(panel, from_node=from_node)
        return self




    # =============================================================================================================================
    # Gizmo
    # =============================================================================================================================

    @property
    def pin_gizmo(self):
        self._is_empty("No gizmo is possible.")
        return self._bsocket.pin_gizmo

    @pin_gizmo.setter
    def pin_gizmo(self, value):
        self._is_empty("No gizmo is possible.")
        self._bsocket.pin_gizmo = value

    # ====================================================================================================
    # A dynamic attribute can be:
    # - a peer socket : an output socket of the owning node
    # - a group method
    # To avoid names collision, the attribute name can be suffixed by '_' which is ignored
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Get attr
    # ----------------------------------------------------------------------------------------------------

    def __getattr__(self, name):

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

        self._is_empty(f"Impossible to get an attribute from an empty socket (name: '{name}')")

        # Ignore the ending '_' char
        true_name = name
        if name[-1] == '_':
            true_name = name[:-1]
            if true_name == "" or true_name[-1] == '_':
                raise AttributeError(f"Socket {self} doesn't have peer socket named '{name}'")

        sc_name = utils.snake_case(true_name)

        # ---------------------------------------------------------------------------
        # Another node output socket
        # ---------------------------------------------------------------------------

        socket = self.node.get_socket('OUTPUT', true_name, None, halt=False)
        if socket is not None:
            return socket

        # ---------------------------------------------------------------------------
        # A group
        # ---------------------------------------------------------------------------

        trees = utils.get_available_groups(self.node._tree._btree.bl_idname)
        node_tree = None
        for group_name, spec in trees.items():
            if utils.snake_case(group_name) == sc_name:
                node_tree = blender.load_node_group(spec)
                break

        if node_tree is not None:

            def group_call(named_sockets={}, **sockets):

                all_sockets = {**named_sockets, **sockets}

                new_sockets = {**named_sockets}

                check_selec = 'Selection' not in all_sockets and 'selection' not in all_sockets and self._socket_type == 'GEOMETRY'

                interf = TreeInterface(node_tree)
                socks = interf.get_sockets('INPUT')
                for isock, sock in enumerate(socks):

                    # Current socket is the proper type
                    if SocketType(sock) == self._socket_type:
                        if sock.name not in all_sockets and utils.snake_case(sock.name) not in all_sockets:

                            # Set value to self
                            new_sockets[sock.name] = self

                            # Selection following a Geometry 
                            if check_selec and isock < len(socks) - 1:
                                next_sock = socks[isock + 1]
                                if next_sock.name == 'Selection' and SocketType(next_sock) == 'BOOLEAN':
                                    new_sockets['Selection'] = self.get_selection()
                            break

                return Group(node_tree.name, named_sockets = new_sockets, **sockets)._out

            # Returns the function creating the group with the proper arguments
            return group_call

        # ---------------------------------------------------------------------------
        # Error message
        # ---------------------------------------------------------------------------

        is_node = true_name in dir(self.node)

        node_names = list(set([sock.name for sock in self.node._bnode.outputs]))
        tree_names = list(trees.keys())

        node_prox = utils.prox_names(true_name, node_names)
        tree_prox = utils.prox_names(true_name, tree_names)

        if is_node:
            msg = f"Perhaps you want to call the node method '{true_name}', use syntax: 'socket.node.{true_name}(...)' instead of 'socket.{true_name}'"
        elif len(node_prox):
            msg = f"Perhaps you wanted to access the peer socket '{node_prox[0]}' ({utils.snake_case(node_prox[0])})"
        elif len(tree_prox):
            msg = f"Perhaps you wanted to call the group '{tree_prox[0]}' ({utils.snake_case(tree_prox[0])})"
        else:
            msg = f"If you try to access a peer socket, the node sockets are given below:\n{repr(self.node)}"

        ne = NodeError(f"{type(self).__name__} socket doesn't have an attribute named '{name}'.\n{msg}")

        raise AttributeError(str(ne))

    # ====================================================================================================
    # Test a value in a list
    # ====================================================================================================

    @staticmethod
    def check_in_list(value, valids, context=""):
        if value in valids:
            return True
        raise NodeError(f"{context} value error: '{value}' is not valid.", valids=valids)

    # ====================================================================================================
    # To output
    # ====================================================================================================

    def out(self, name: str = None, panel: str = "", **props):
        """ Plug the value to the Group Output Node.

        ``` python
        with GeoNodes("Plug to group output"):
            # Create a cube
            geo = Mesh.Cube()
            # To Group Output geometry as socket named "Cube"
            geo.out("Cube")
        ```

        The "Do nothing" modifier is simply ``` Geometry().out() ```

        Parameters
        ----------
        name : str, optional
            socket name default=None.


        Returns
        -------
        None
        """
        self._is_empty(f"Impossible to link an empty socket (name: '{name}').")

        out_node = self._tree.get_output_node()
        out_node.set_input_socket(name=name, value=self, create=True, panel=panel, **props)

    @classmethod
    def Out(cls, value, name: str = None, panel: str = "", **props):
        """Send a value to the current group or zone output.

        Constants are assigned directly to the output node's input, without
        creating a constant node. Socket.Out infers the type; subclasses such
        as Float.Out explicitly select the output type.

        ``` python
        Socket.Out(3.14, "Pi")
        Float.Out(1, "Factor")
        Socket.Out(value, "Result")
        ```

        Parameters
        ----------
        value : Any
            Constant or socket to output.
        name : str, optional
            Output socket name.
        panel : str, optional
            Output panel.
        **props
            Properties used when creating the output socket.

        Returns
        -------
        None
        """
        tree = Tree.current_tree()
        if tree is None:
            raise NodeError("Socket.Out requires an active tree.")

        if isinstance(value, Socket):
            value._is_empty(f"Impossible to link an empty socket (name: '{name}').")

        out_node = tree.get_output_node()
        if cls.SOCKET_TYPE is None:
            if name is None and utils.get_bsocket(value) is None:
                name = SocketType(value).class_name
            out_node.set_input_socket(name=name, value=value, create=True, panel=panel, **props)
            return

        socket_type = SocketType.from_type(cls.SOCKET_TYPE)
        full_name = None if name is None else (ItemPath(panel) + name).path
        socket = out_node.get_socket('INPUT', full_name, socket_type,
                                     free_only=True, halt=False)
        if socket is None:
            if name is None:
                name = socket_type.class_name
            socket = out_node.create_socket('INPUT', socket_type, name=name, panel=panel, **props)
        out_node.set_input_socket_value(socket, value)

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

    def _push(self):

        from .treeclass import Layout

        self.node._push()

        # Push a Layout dedicated this context
        # (will be removed by arrange if no node is created)
        if self._use_layout:
            self._layout = Layout()
            self._layout.push()

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

        self.node._pop(error)

        # Pop inout capture and layout
        if self._use_layout:
            self._layout.pop()

    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)

    # ====================================================================================================
    # Menu Switch
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Constructor version
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def MenuSwitch(cls, 
                   named_sockets    : dict = {},
                   default_menu     : str = None,
                   **sockets):
        """ > Node Menu Switch

        The items of the Menu Switch node are provided in the 'items' dict.

        Parameters
        ----------
        named_sockets : dict, optional
            sockets to create default={}.

        default_menu : str, optional
            default menu value default=None.

        sockets : dict
            items


        Returns
        -------
        Socket
        """
        node = Node('Menu Switch',
                named_sockets = named_sockets,
                data_type = SocketType.from_type(cls.SOCKET_TYPE).type,
                #default_menu = default_menu,
                **sockets)
        node._default_menu = default_menu

        return cls(node._out)

    # ----------------------------------------------------------------------------------------------------
    # Method version
    # ----------------------------------------------------------------------------------------------------

    def menu_switch(self,
                self_name       : str = 'Self', 
                named_sockets   : dict = {},
                default_menu    : str = None,
                **sockets):
        """ > Node Menu Switch

        [&NO_JUMP]

        Self is connected to the first menu item with the name provided as argument.

        The items of the Menu Switch node are provided in the 'items' dict.
        An group input socket named after the 'name' argument is linked to menu selector.

        Parameters
        ----------
        named_sockets : dict, optional
            sockets to create default={}.

        default_menu : str, optional
            default menu value default=None.

        sockets : dict
            items


        Returns
        -------
        Socket
        """        
        return self.MenuSwitch(named_sockets = {self_name: self, **named_sockets}, default_menu=default_menu, **sockets)

    # ====================================================================================================
    # Setting the menu
    # ====================================================================================================

    @property
    def menu(self):
        raise NodeError(f"Menu Switch error: 'menu' is a write only property.")

    @menu.setter
    def menu(self, value):
        if self.node._bnode.bl_idname != 'GeometryNodeMenuSwitch':
            raise NodeError(f"Impossible to set the menu, the socket {self} is not the output of a [Menu Switch] node")

        self.node.set_input_socket("menu", value)


    # ====================================================================================================
    # Index Switch
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Constructor version
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def IndexSwitch(cls, *values, index = None, default_index: int = 0):
        """ > Node Index Switch

        ``` python
        with GeoNodes("IndexSwitch demo"):

            # Create some geometries
            geo    = Geometry()
            cube   = Mesh.Cube()
            sphere = Mesh.IcoSphere()
            cone   = Mesh.Cone()

            # Pick in this list
            pick_geo = Geometry.IndexSwitch(geo, cube, sphere, cone, index=tree.new_input("Geometry index", default_value=2))

            # Plug the result to the output
            pick_geo.out()
        ```

        Parameters
        ----------
        *values : Any
            List of Sockets to select into

        index : Integer, optional
            socket 'Index' (Index) default=None.

        default_index : int, optional
            default idex default=0.


        Returns
        -------
        Socket
        """
        node = Node('Index Switch', 
                        {str(i): value for i, value in enumerate(values)}, 
                        data_type=cls.SOCKET_TYPE, 
                        Index=index)
        return cls(node._out)

    # ----------------------------------------------------------------------------------------------------
    # Method version
    # ----------------------------------------------------------------------------------------------------

    def index_switch(self, *values, index = None, default_index: int = 0):
        """ > Node Index Switch

        ``` python
        with GeoNodes("index_switch demo") as tree:

            # Create some geometries
            geo    = Geometry()
            cube   = Mesh.Cube()
            sphere = Mesh.IcoSphere()
            cone   = Mesh.Cone()

            # Pick in this list
            pick_geo = geo.index_switch(cube, sphere, cone, index=tree.new_input("Geometry index", default_value=2))

            # Plug the result to the output
            pick_geo.out()
        ```

        Parameters
        ----------
        *values : Any
            List of Sockets to select into

        index : Integer, optional
            socket 'Index' (Index)

        default_index : int, default=0
            default idex

        Returns
        -------
        Socket
        """
        return self.IndexSwitch(self, *values, index=index, default_index=default_index)

    # ====================================================================================================
    # Switch
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Constructor version
    # ----------------------------------------------------------------------------------------------------

    @classmethod
    def Switch(cls, condition=None, false=None, true=None):
        """ > Node Switch

        ``` python
        with GeoNodes("Switch demo"):

            # Two possible geometries
            cube   = Mesh.Cube()
            sphere = Mesh.IcoSphere()

            # Select
            geo = Geometry.Switch(Boolean(True, "Use Sphere"), cube, sphere)

            # To group output
            geo.out()
        ```

        Parameters
        ----------
        condition : Boolean
            socket 'Switch' (Switch)

        false
            socket 'False' (False)

        true
            socket 'True' (True)


        Returns
        -------
        Socket
            Socket wrapped in the calling class (for example, Mesh.Switch returns Mesh).
        """
        input_type = SocketType.from_type(cls.SOCKET_TYPE).items_type
        node = Node('Switch', {'Switch': condition, 'False': false, 'True': true}, input_type=input_type)
        return cls(node._out)

    # ----------------------------------------------------------------------------------------------------
    # Method version
    # ----------------------------------------------------------------------------------------------------

    def switch(self, condition=None, true=None):
        """ > Node Switch

        Self is connected to 'false' socket.

        !!! note
            switch returns self if global constant SWITCH_JUMP = True (default)
            set SWITCH_JUMP = False for legacy behavior

        ``` python
        with GeoNodes("Switch demo"):

            from geonodes import core_module
            constants = core_module.constants
            # Legacy behavior (default is True)
            constants.SWITCH_JUMP = False

            choice = Boolean(True, "Use Sphere")

            # Two possible geometries
            cube   = Mesh.Cube()
            sphere = Mesh.IcoSphere()

            # Select
            # Legacy behavior: cube is unchanged otherwise cube
            geo = cube.switch(choice, sphere)

            # To group output
            geo.out()
        ```

        Information
        -----------
        - Socket 'False' : self

        Parameters
        ----------
        condition : Boolean
            socket 'Switch' (Switch)

        true
            socket 'True' (True)


        Returns
        -------
        Socket (self)
        """
        res = self.Switch(condition=condition, false=self, true=true)
        if constants.SWITCH_JUMP:
            return self._jump(res)
        else:
            return res

    # ----------------------------------------------------------------------------------------------------
    # Alternative method version
    # ----------------------------------------------------------------------------------------------------

    def switch_false(self, condition=None, false=None):
        """ > Node Switch

        [&JUMP]

        Self is connected to 'true' socket.

        !!! important
            This methods behaves the inverse of switch : self is connected to "True" socket and  the argument to "False", socket

        !!! note
            This method is mainly provided to cover the case when 'False' socket is None

        ``` python
        with GeoNodes("Switch demo"):

            geo = Geometry()

            show_geometry = Boolean(False, "Merge with Cube")

            cube = Mesh.Cube()

            geo += cube.switch_false(show_geometry)

            # Is equivalent to
            geo += Geometry.Switch(show_geometry, None, cube)

            # To group output
            geo.out()
        ```

        !!! note
            This method let self socket unchanged. To set self socket to the result

        Information
        -----------
        - Socket 'True' : self

        Parameters
        ----------
        condition : Boolean
            socket 'Switch' (Switch)

        false
            socket 'False' (False)


        Returns
        -------
        Socket
        """
        res = self.Switch(condition=condition, false=false, true=self)
        if constants.SWITCH_JUMP:
            return self._jump(res)
        else:
            return res

    # ====================================================================================================
    # Loops
    # ====================================================================================================

    # ----------------------------------------------------------------------------------------------------
    # Repeat
    # ----------------------------------------------------------------------------------------------------

    def repeat(self, iterations=1, named_sockets: dict={}, **sockets):
        """ Repeat zone

        Parameters
        ----------
        iterations : Integer, default=1
            iteration socket

        named_sockets : dict, default={}
            named sockets

        sockets : dict, optional
            other sockets


        Returns
        -------
        ZoneIterator
        """
        class_name = type(self).__name__
        node = ZoneNode("Repeat", named_sockets={class_name: self, **named_sockets}, Iterations=iterations, **sockets)
        return ZoneIterator(self, node)

    # ----------------------------------------------------------------------------------------------------
    # Simulation
    # ----------------------------------------------------------------------------------------------------

    def simulation(self, named_sockets: dict={}, **sockets):
        """ Simulation zone

        Parameters
        ----------
        named_sockets : dict, default={}
            named sockets

        sockets : dict, optional
            other sockets

        Returns
        -------
        ZoneIterator
        """
        class_name = type(self).__name__
        node = ZoneNode("Simulation", named_sockets={class_name: self, **named_sockets}, **sockets)
        return ZoneIterator(self, node)

    # ====================================================================================================
    # Add the current tree as Socket method
    # ====================================================================================================

    def add_method(self, name: str = None, jump: bool = False, ret_class: type = None, **fixed):
        """ Add the current tree as a method of the Socket class.

        !!! important

            The socket instance must be an input socket of the Tree. This input plays the role of
            self argument.

        ``` python
        with GeoNodes("Translate"):
            geo = Geometry()
            v = Vector(0, "Translation)
            geo.transform(translation=v)

            geo.add_method(jump=True)
        ```

        Once the modifier completed, it can be called as a method of geometry ```geo.translate(translation=(1, 2, 3))```

        Parameters
        ----------
        name : str, optional
            replace the default name which is the snake case version of the group name default=None.

        ret_class : type, optional
            transtype the default node output default=None.

        jump : bool, optional
            the calling socket jumps to the node outpus after the call default=False.

        ret_class : type, optional
            transtype the result with this class if not None default=None.

        """

        if self.node._bnode.bl_idname != 'NodeGroupInput':
            raise NodeError(
                f"'add_method' can be called only from a 'Group Input' socket. "
                "This socket is used a 'self' argument when calling the method of {type(self).__name__}.")

        tree = Tree.current_tree()

        # ---------------------------------------------------------------------------
        # Method Body
        # ---------------------------------------------------------------------------

        socket_rank = self.node._outputs.get_socket_rank(self)
        socket_name = utils.snake_case(self._bsocket.name)


        def call(self_, *args, **kwargs):
            node = Group(tree._btree.name)
            if socket_rank >= len(args):
                new_args = args
                new_kwargs = {socket_name: self_, **kwargs}
            else:
                new_args = args[:socket_rank] + (self_,) + args[socket_rank:]
                new_kwargs = kwargs

            res = node.method_call(*new_args, ret_class=ret_class, **new_kwargs, **fixed)

            if jump:
                return self_._jump(res)
            else:
                return res

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

        if name is None:
            name = tree._btree.name[len(tree._prefix):].strip()
            name = utils.snake_case(name)

        class_ = type(self)
        if name in dir(class_):
            print(f"CAUTION: the method '{name}' (implementing group '{tree._btree.name}') already exists in class {class_}.")

        setattr(class_, name, call)


    # ====================================================================================================
    # Class Test
    # ====================================================================================================

    @staticmethod
    def _test_socket_to_data_type():

        from .utils import SOCKET_CLASSES
        from pprint import pprint

        # ----------------------------------------------------------------------------------------------------
        # Create the test tree
        # ----------------------------------------------------------------------------------------------------

        tree = bpy.data.node_groups.get("Test")
        if tree is None:
            tree = bpy.data.node_groups.new("Test", 'GeometryNodeTree')

        tree.nodes.clear()

        # ----------------------------------------------------------------------------------------------------
        # Loop on nodes
        # ----------------------------------------------------------------------------------------------------

        tested_nodes        = {}
        tests               = {}
        data_type_to_socket = {}
        socket_to_data_type = {}
        orphans             = set()
        mults               = set()

        for type_name in dir(bpy.types):

            # Create the node

            try:
                node = tree.nodes.new(type_name)
            except:
                continue

            # data_type and input_type params

            T = type(node)
            param_name = None
            for name in ['data_type', 'input_type']:
                if name in dir(node):
                    param_name = name
                    break

            if param_name is None:
                continue

            # List of valid identifier
            # dt_to_sock : all socket types giving the data_type

            dt_to_sock = {enum.identifier: [] for enum in T.bl_rna.properties[param_name].enum_items}

            # Register
            tested_nodes[node.name] = {'param_name': param_name, 'enums': tuple(dt_to_sock.keys())}

            # Test identical lists once
            key = str(set(dt_to_sock.keys()))
            if key in tests:
                tests[key]['nodes'].append(node.name)
                continue

            # loop on SOCKET_TYPE

            sock_to_dt = {}
            for socket_type in SOCKET_CLASSES:

                st = SocketType.from_type(socket_type)

                # The core method to test
                dt = st.convert_type_for_node(socket_type, node.bl_idname, param_name, on_error='NONE')

                # We have a result
                if dt is not None:
                    sock_to_dt[st.class_name] = dt
                    dt_to_sock[dt].append(st.class_name)

                    l = socket_to_data_type.get(st.class_name, set())
                    l.add(dt)
                    socket_to_data_type[st.class_name] = l

                    l = data_type_to_socket.get(dt, set())
                    l.add(st.class_name)
                    data_type_to_socket[dt] = l


            # Register the result
            tests[key] = {
                "nodes"      : [node.name],
                "sock_to_dt" : sock_to_dt,
                "dt_to_sock" : dt_to_sock,
                }

            # Check that all possible choices are reached
            # Could happen with the node 'Store Named Attribute' for instance

            node_orphans = set()
            node_mults = set()
            for k, v in dt_to_sock.items():
                if len(v) == 0:
                    node_orphans.add(k)
                elif len(v) > 1:
                    node_mults.add((k, tuple(v)))

            orphans = orphans.union(node_orphans)
            mults = mults.union(node_mults)

        # ----------------------------------------------------------------------------------------------------
        # Print the results
        # ----------------------------------------------------------------------------------------------------

        print('-'*100)
        print("Test Socket to data_type")
        print('-'*100)
        print()
        print(f"Nodes: {len(tested_nodes)}")
        for k, v in tested_nodes.items():
            print(f"- {k:25s} : {v['param_name']}")
        print()

        print(f"Enums: {len(tests)}")
        for k, v in tests.items():
            print(f"{len(v['nodes'])} :", tuple(v['dt_to_sock'].keys()))        
        print()

        print("Socket -> data_type")
        for k, v in socket_to_data_type.items():
            print(f"- {k:15s} :", v)
        print()

        print("data_type -> Socket")
        for k, v in data_type_to_socket.items():
            print(f"- {k:15s} :", v)
        print()

        print("Orphans: data_type not coming from a Socket")
        pprint(orphans)
        print()

        print("Mults: sockets giving the same data_type")
        pprint(mults)
        print()

    @staticmethod
    def _class_test():

        from .utils import SOCKET_CLASSES
        from .geonodes import GeoNodes
        from .geometry_class import Geometry
        from .sock_float import Float
        from .treeclass import Layout
        from .sock_color import Color
        from .sock_rotation import Rotation
        from .sock_vector import Vector
        from .sock_matrix import Matrix
        from .sock_bundle import Bundle
        from .sock_integer import Integer
        from .generated import nd

        Socket._test_socket_to_data_type()

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

            # Create inputs
            for stype, klass in SOCKET_CLASSES.items():
                if stype == 'SHADER':
                    continue
                class_name = klass.__name__
                a = klass(name=class_name)

            # Getting existing inputs
            for stype, klass in SOCKET_CLASSES.items():
                if stype in ['SHADER', 'MENU']:
                    continue
                class_name = klass.__name__
                klass.Input(class_name).out(f"Out {class_name}")

            # Constants
            with Layout("Constants"):
                for stype, klass in SOCKET_CLASSES.items():
                    if stype == 'SHADER':
                        continue
                    a = klass()

            # Arrays
            with Layout("Colors"):
                Color(.8).out(panel="Color")
                Color((.1, .2, .3)).out(panel="Color")
                Color((.1, .2, .3, .4)).out(panel="Color")
                Color(Float(.89)).out(panel="Color")
                Color((Float(.5), 0, 0)).out(panel="Color")
                Color((0, Float(.5), 1)).out(panel="Color")
                Color((Float(.5), Float(.5), Float(.5), Float(.5))).out(panel="Color")

            with Layout("Vector"):
                Vector(.8).out(panel="Vector")
                Vector((.1, .2, .3)).out(panel="Vector")
                Vector(Float(.89)).out(panel="Vector")
                Vector((Float(.5), 0, 0)).out(panel="Vector")
                Vector((0, Float(.5), 1)).out(panel="Vector")
                Vector((Float(.5), Float(.5), Float(.5))).out(panel="Vector")

            with Layout("Rotation"):
                Rotation(.8).out(panel="Rotation")
                Rotation((.1, .2, .3)).out(panel="Rotation")
                Rotation(Float(.89)).out(panel="Rotation")
                Rotation((Float(.5), 0, 0)).out(panel="Rotation")
                Rotation((0, Float(.5), 1)).out(panel="Rotation")
                Rotation((Float(.5), Float(.5), Float(.5))).out(panel="Rotation")

            with Layout("Matrix"):
                Matrix(.8).out(panel="Matrix")
                Matrix([i for i in range(16)]).out(panel="Matrix")
                Matrix([Float(i) for i in range(16)]).out(panel="Matrix")

        with GeoNodes("List Tests"):

            geo = Geometry()

            with Bundle() as bundle:

                l = Matrix().separate_to_list()
                l.reshape_list((4, 4))
                l.reshape_list(16)
                m = Matrix.FromList(l)
                m.out()

                l = Vector().separate_to_list()
                v = Vector.FromList(l)
                v.out()

                l = Color().separate_to_list()
                c = Color.FromList(l)
                c.out()

                l = Rotation().separate_to_list()
                r = Rotation.FromList(l)
                r.out()

                l = (nd.index*2.0).to_list(10)
                l.list_append(22)
                ol = (nd.index*10.0).to_list(5)
                l.list_append(ol)
                l.list_length().not_equal(16).warning("List length 16 expected")
                l.out()

                Float(6.28*nd.index).field_to_list(Rounds_Count=nd.index, count=10).node.out()
                Integer.List(*[2**i for i in range(8)]).out("Powers of 2")


            geo.set_bundle(bundle)
            geo.out()

_interface_socket property

Return the interface socket if exists

An interface socket exists when the socket a tree input or output socket or when it is the socket of a group

Returns:

Type Description
Interface Socket

_is_list property

bool property

Returns True if socket is a list

_name property

Return the name or the label

Returns:

Type Description
str

default is ""

_panel_name property

Return the name of the panel

Returns:

Type Description
str

default is ""

is_grid property

bool property

Returns True if socket is a grid (inferred_structure_type == 'GRID').

len property

Short cut for 'self.list_length()'

node_color property writable

Node color

Returns:

Type Description
SysColor

node_label property writable

Node Label

Returns:

Type Description
str

Constant(value, user_label='') classmethod

Create an input socket from a constant Node.

Parameters:

Name Type Description Default
value Any

constant default value default=None.

required
user_label str

socket name (used to rename nodes if not None) default="".

''
Source code in core/socket_class.py
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
@classmethod
def Constant(cls, value: None, user_label: str = ""):
    """ Create an input socket from a constant Node.

    Parameters
    ----------
    value : Any, optional
        constant default value default=None.

    user_label : str, optional
        socket name (used to rename nodes if not None) default="".
    """

    # ---------------------------------------------------------------------------
    # Ensure array
    # ---------------------------------------------------------------------------

    def get_shaped(v, *shapes):
        r = np.ravel(v)
        shape = np.shape(r)
        if shape in shapes:
            return tuple(r)

        if shape == (1,):
            return tuple(np.resize(r, shapes[0]))

        raise NodeError(
            f"The value <{v}> can't be transformed in a valid initial value for {SocketType.from_type(cls.SOCKET_TYPE).class_name}."
        )

    # ---------------------------------------------------------------------------
    # Does the array contain sockets
    # ---------------------------------------------------------------------------

    def has_sockets(a):
        for v in a:
            if SocketType.get_bsocket(v) is not None:
                return True
        return False

    # ---------------------------------------------------------------------------
    # Default value
    # ---------------------------------------------------------------------------

    socket_type = SocketType.from_type(cls.SOCKET_TYPE)
    if cls.SOCKET_TYPE not in ['RGBA', 'VECTOR', 'ROTATION', 'MATRIX']:
        def_val = socket_type.get_default_from_value(value)

    # ---------------------------------------------------------------------------
    # Depending on the socket type
    # ---------------------------------------------------------------------------

    if cls.SOCKET_TYPE == 'BOOLEAN':
        return Node('Boolean', boolean=def_val)._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'BUNDLE':
        return Node("Combine Bundle")._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'CLOSURE':
        socket = ZoneNode.Closure().closure
        socket._use_layout = False
        return socket._ul(user_label)

    elif cls.SOCKET_TYPE == 'COLLECTION':
        return Node('Collection', collection=def_val)._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'RGBA':

        if value is None:
            a = (0, 0, 0, 1)
        elif isinstance(value, str):
            #a = colors.to_color(value)
            a = SysColor(value).rgba
        else:
            a = get_shaped(value, (4,), (3,))

        if has_sockets(a):
            if Tree.is_geonodes():
                node = Node('Combine Color', {0: a[0], 1: a[1], 2:a[2]})
                if len(a) == 4:
                    node.alpha = a[3]
                return node._out._ul(user_label)
            else:
                return Node('Combine Color', {0: a[0], 1: a[1], 2:a[2]})._out._ul(user_label)

        else:
            def_val = SocketType.from_type('COLOR').get_default_from_value(a)
            if Tree.is_geonodes():
                return Node('Color', value=def_val)._out._ul(user_label)

            else:
                socket = Node('Color')._out
                socket._bsocket.default_value = def_val
                return socket._ul(user_label)

    elif cls.SOCKET_TYPE == 'IMAGE':
        return Node('Image', image=def_val)._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'INT':
        return Node('Integer', integer=def_val)._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'MATERIAL':
        return Node('Material', material=def_val)._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'MATRIX':

        if value is None:
            a = (1, 0, 0, 0,   0, 1, 0, 0,   0, 0, 1, 0,   0, 0, 0, 1)
        else:
            a = get_shaped(value, (16,))

        return Node('Combine Matrix', named_sockets = {i: a[i] for i in range(16)})._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'MENU':
        if True: # V5.2
            from .generated.static_nd import ND
            return ND.menu(value)
            #return Node('Menu', value=value)._out._ul(user_label)
        else:
            return Node('Menu Switch')._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'OBJECT':
        return Node('Object', object=def_val)._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'FONT':
        if True: # V5.2
            return Node('Font', font=def_val)._out._ul(user_label)
        else:
            return cls.NewInput("Font", value)

    elif cls.SOCKET_TYPE == 'ROTATION':

        if value is None:
            a = (0, 0, 0)
        else:
            a = get_shaped(value, (3,))

        if has_sockets(a):
            return Node('Combine XYZ', x=a[0], y=a[1], z=a[2])._out.to_rotation()._ul(user_label)
        else:
            return Node('Rotation', rotation_euler=a)._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'STRING':
        return Node('String', string=def_val)._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'VALUE':
        node = Node('Value')
        node._bnode.outputs[0].default_value = def_val
        return node._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'VECTOR':

        if value is None:
            a = (0, 0, 0)
        else:
            a = get_shaped(value, (3,))

        if has_sockets(a):
            return Node('Combine XYZ', x=a[0], y=a[1], z=a[2])._out._ul(user_label)
        else:
            return Node('Vector', vector=a)._out._ul(user_label)

    elif cls.SOCKET_TYPE == 'GEOMETRY':
        raise NodeError(f"There is no node to create a Geometry. Use explicit constructors such as 'Mesh.Cube()', 'Curve.Spiral()' or 'Cloud.Points().")

    else:
        assert False, f"Shouldn't happen {socket_type}"

Empty(value=None) classmethod

Create an empty socket.

An empty socket is used temporarily as an input for nodes with dynamic sockets:

Parameters:

Name Type Description Default
value Any

default value default=None.

None
Source code in core/socket_class.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
@classmethod
def Empty(cls, value = None):
    """ Create an empty socket.

    An empty socket is used temporarily as an input for nodes with dynamic sockets:

    Parameters
    ----------
    value : Any, optional
        default value default=None.

    """
    socket = cls(constants.EMPTY_SOCKET)
    socket._bsocket = SocketType.from_type(cls.SOCKET_TYPE).get_default_from_value(value)
    return socket

IndexSwitch(*values, index=None, default_index=0) classmethod

Node Index Switch

with GeoNodes("IndexSwitch demo"):

    # Create some geometries
    geo    = Geometry()
    cube   = Mesh.Cube()
    sphere = Mesh.IcoSphere()
    cone   = Mesh.Cone()

    # Pick in this list
    pick_geo = Geometry.IndexSwitch(geo, cube, sphere, cone, index=tree.new_input("Geometry index", default_value=2))

    # Plug the result to the output
    pick_geo.out()

Parameters:

Name Type Description Default
*values Any

List of Sockets to select into

()
index Integer

socket 'Index' (Index) default=None.

None
default_index int

default idex default=0.

0

Returns:

Type Description
Socket
Source code in core/socket_class.py
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
@classmethod
def IndexSwitch(cls, *values, index = None, default_index: int = 0):
    """ > Node Index Switch

    ``` python
    with GeoNodes("IndexSwitch demo"):

        # Create some geometries
        geo    = Geometry()
        cube   = Mesh.Cube()
        sphere = Mesh.IcoSphere()
        cone   = Mesh.Cone()

        # Pick in this list
        pick_geo = Geometry.IndexSwitch(geo, cube, sphere, cone, index=tree.new_input("Geometry index", default_value=2))

        # Plug the result to the output
        pick_geo.out()
    ```

    Parameters
    ----------
    *values : Any
        List of Sockets to select into

    index : Integer, optional
        socket 'Index' (Index) default=None.

    default_index : int, optional
        default idex default=0.


    Returns
    -------
    Socket
    """
    node = Node('Index Switch', 
                    {str(i): value for i, value in enumerate(values)}, 
                    data_type=cls.SOCKET_TYPE, 
                    Index=index)
    return cls(node._out)

Input(name, panel='', halt=True) classmethod

Get an exist input socket from its name and panel.

Note

The "input" socket here is an "output" socket of the current input node

To create a input socket use NewInput.

If the 'name' argument is None, the first socket of the proper type is returned.

Raises:

Type Description
- NodeError if socket is not found and halt is requested

Parameters:

Name Type Description Default
name str | None

socket name

required
panel str

panel name default="".

''
halt bool

raises an error if not found default=True.

True

Returns:

Type Description
Socket
Source code in core/socket_class.py
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
@classmethod
def Input(cls, name: str, panel: str = "", halt: bool = True):
    """ Get an exist input socket from its name and panel.

    !!! note
        The "input" socket here is an "output" socket of the current input node

    To create a input socket use NewInput.

    If the 'name' argument is None, the first socket of the proper type is returned.

    Raises
    ------
    - NodeError if socket is not found and halt is requested

    Parameters
    ----------
    name : str | None
        socket name

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

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


    Returns
    -------
    Socket
    """
    in_node = Tree.current_tree().get_input_node()

    include = None if name is None else [name]
    bsockets = in_node.get_sockets('OUTPUT', include=include, panel=panel)

    for _, bsock in bsockets:
        if SocketType(bsock).type == cls.SOCKET_TYPE: # and utils.snake_case(sock_name) == utils.snake_case(name):
            return cls(bsock._bsocket)._ul(name)

    if halt:
        sname = "" if name is None else f" named '{name}'"
        raise NodeError(
            f"There is no {SocketType.from_type(cls.SOCKET_TYPE).class_name} input socket{sname}.\n"
            f"Available sockets are : {[bsock[0] for bsock in in_node.get_sockets('OUTPUT')]}.")

    return None

List(*items, name='') classmethod

Create a Blender List from items.

Parameters:

Name Type Description Default
items Any

Items to put in the list.

()
name str

socket name default="".

''

Returns:

Type Description
- Socket List
Source code in core/socket_class.py
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
@classmethod
def List(cls, *items, name: str = ""):
    """ Create a Blender List from items.

    Parameters
    ----------
    items : Any, optional
        Items to put in the list.

    name : str, optional
        socket name  default="".

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

    from .sock_closure import Closure
    from .sock_integer import Integer

    with Closure() as cl:

        idx = Integer(0, "Index")

        if True:
            value = cls.IndexSwitch(*items, index=idx)
        else:
            with cls.IndexSwitch(index=idx) as value:
                for item in items:
                    cls(item).out()

        if name == "":
            name = cls.__name__
        value.out(name)

    return cls(cl.to_list(count=len(items)))

MenuSwitch(named_sockets={}, default_menu=None, **sockets) classmethod

Node Menu Switch

The items of the Menu Switch node are provided in the 'items' dict.

Parameters:

Name Type Description Default
named_sockets dict

sockets to create default={}.

{}
default_menu str

default menu value default=None.

None
sockets dict

items

{}

Returns:

Type Description
Socket
Source code in core/socket_class.py
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
@classmethod
def MenuSwitch(cls, 
               named_sockets    : dict = {},
               default_menu     : str = None,
               **sockets):
    """ > Node Menu Switch

    The items of the Menu Switch node are provided in the 'items' dict.

    Parameters
    ----------
    named_sockets : dict, optional
        sockets to create default={}.

    default_menu : str, optional
        default menu value default=None.

    sockets : dict
        items


    Returns
    -------
    Socket
    """
    node = Node('Menu Switch',
            named_sockets = named_sockets,
            data_type = SocketType.from_type(cls.SOCKET_TYPE).type,
            #default_menu = default_menu,
            **sockets)
    node._default_menu = default_menu

    return cls(node._out)

Named(name) classmethod

Node Named Attribute

Information
  • Parameter 'data_type' : 'BOOLEAN'

Parameters:

Name Type Description Default
name String

socket 'Name' (id: Name)

required

Returns:

Type Description
Boolean
Source code in core/socket_class.py
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
@classmethod
def Named(cls, name):
    """ > Node Named Attribute

    Information
    -----------
    - Parameter 'data_type' : 'BOOLEAN'

    Parameters
    ----------
    name : String
        socket 'Name' (id: Name)


    Returns
    -------
    Boolean
    """
    if SocketType.from_type(cls.SOCKET_TYPE).class_name not in constants.ATTRIBUTE_CLASSES:
        raise NodeError(
            f"The class {SocketType.from_type(cls.SOCKET_TYPE).class_name} is not an attribute.\n"
            f"Attribute classes are: {constants.ATTRIBUTE_CLASSES}")

    node = Node('Named Attribute', name=name)
    data_type = SocketType.from_type(cls.SOCKET_TYPE).get_node_data_type(
        tree_type = node._tree._btree.bl_idname,
        bl_idname = node._bnode.bl_idname,
        halt = True)

    node.set_parameter('data_type', data_type)

    return node._out._ul(name)

NewInput(name, value=None, tip='', panel='', **props) classmethod

Create an new input socket

Note

The "input" socket here is an "output" socket of the current input node

To get an existing input socket use Input.

Raises:

Type Description
- NodeError if socket is not found

Parameters:

Name Type Description Default
name str

socket name

required
value Any

default_value default=None.

None
tip str

description default="".

''
panel str: None

panel name

''

Returns:

Type Description
Socket
Source code in core/socket_class.py
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
@classmethod
def NewInput(cls,
        name: str, 
        value       = None, 
        tip: str    = "", 
        panel: str  = "", 
        **props):
    """ Create an new input socket

    !!! note
        The "input" socket here is an "output" socket of the current input node

    To get an existing input socket use Input.

    Raises
    ------
    - NodeError if socket is not found

    Parameters
    ----------
    name : str
        socket name

    value : Any, optional
        default_value default=None.

    tip : str, optional
        description default="".

    panel : str: None
        panel name


    Returns
    -------
    Socket
    """
    if value is None:
        defval = None
    else:
        defval = SocketType.from_type(cls.SOCKET_TYPE).get_default_from_value(value)
        new_props = {**props}

        if 'default' in new_props:
            new_props['default'] = defval

        elif 'default_value' in new_props:
            new_props['default_value'] = defval

        else:
            if 'default' not in constants.SOCKETS[cls.SOCKET_TYPE]['props']:
                raise NodeError(f"The {SocketType.from_type(cls.SOCKET_TYPE).class_name} socket doesn't accept a default value. Value argument <{value}> is invalid.")

            new_props['default_value'] = defval

        props = new_props

    return cls(Tree.current_tree().create_input_socket(
        SocketType.from_type(cls.SOCKET_TYPE).socket_id,
        name         = name,
        tip          = tip,
        panel        = panel,
        **props))

Out(value, name=None, panel='', **props) classmethod

Send a value to the current group or zone output.

Constants are assigned directly to the output node's input, without creating a constant node. Socket.Out infers the type; subclasses such as Float.Out explicitly select the output type.

Socket.Out(3.14, "Pi")
Float.Out(1, "Factor")
Socket.Out(value, "Result")

Parameters:

Name Type Description Default
value Any

Constant or socket to output.

required
name str

Output socket name.

None
panel str

Output panel.

''
**props

Properties used when creating the output socket.

{}

Returns:

Type Description
None
Source code in core/socket_class.py
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
@classmethod
def Out(cls, value, name: str = None, panel: str = "", **props):
    """Send a value to the current group or zone output.

    Constants are assigned directly to the output node's input, without
    creating a constant node. Socket.Out infers the type; subclasses such
    as Float.Out explicitly select the output type.

    ``` python
    Socket.Out(3.14, "Pi")
    Float.Out(1, "Factor")
    Socket.Out(value, "Result")
    ```

    Parameters
    ----------
    value : Any
        Constant or socket to output.
    name : str, optional
        Output socket name.
    panel : str, optional
        Output panel.
    **props
        Properties used when creating the output socket.

    Returns
    -------
    None
    """
    tree = Tree.current_tree()
    if tree is None:
        raise NodeError("Socket.Out requires an active tree.")

    if isinstance(value, Socket):
        value._is_empty(f"Impossible to link an empty socket (name: '{name}').")

    out_node = tree.get_output_node()
    if cls.SOCKET_TYPE is None:
        if name is None and utils.get_bsocket(value) is None:
            name = SocketType(value).class_name
        out_node.set_input_socket(name=name, value=value, create=True, panel=panel, **props)
        return

    socket_type = SocketType.from_type(cls.SOCKET_TYPE)
    full_name = None if name is None else (ItemPath(panel) + name).path
    socket = out_node.get_socket('INPUT', full_name, socket_type,
                                 free_only=True, halt=False)
    if socket is None:
        if name is None:
            name = socket_type.class_name
        socket = out_node.create_socket('INPUT', socket_type, name=name, panel=panel, **props)
    out_node.set_input_socket_value(socket, value)

Switch(condition=None, false=None, true=None) classmethod

Node Switch

with GeoNodes("Switch demo"):

    # Two possible geometries
    cube   = Mesh.Cube()
    sphere = Mesh.IcoSphere()

    # Select
    geo = Geometry.Switch(Boolean(True, "Use Sphere"), cube, sphere)

    # To group output
    geo.out()

Parameters:

Name Type Description Default
condition Boolean

socket 'Switch' (Switch)

None
false

socket 'False' (False)

None
true

socket 'True' (True)

None

Returns:

Type Description
Socket

Socket wrapped in the calling class (for example, Mesh.Switch returns Mesh).

Source code in core/socket_class.py
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
@classmethod
def Switch(cls, condition=None, false=None, true=None):
    """ > Node Switch

    ``` python
    with GeoNodes("Switch demo"):

        # Two possible geometries
        cube   = Mesh.Cube()
        sphere = Mesh.IcoSphere()

        # Select
        geo = Geometry.Switch(Boolean(True, "Use Sphere"), cube, sphere)

        # To group output
        geo.out()
    ```

    Parameters
    ----------
    condition : Boolean
        socket 'Switch' (Switch)

    false
        socket 'False' (False)

    true
        socket 'True' (True)


    Returns
    -------
    Socket
        Socket wrapped in the calling class (for example, Mesh.Switch returns Mesh).
    """
    input_type = SocketType.from_type(cls.SOCKET_TYPE).items_type
    node = Node('Switch', {'Switch': condition, 'False': false, 'True': true}, input_type=input_type)
    return cls(node._out)

__init__(socket=None, name=None, tip='', panel='', user_label=None, **props)

Parameters:

Name Type Description Default
socket NodeSocket

the output socket to wrap default=None.

None
name str

input name if not None default=None.

None
tip str

description default="".

''
panel str

panel name default="".

''
user_label str

user label default=None.

None
Source code in core/socket_class.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def __init__(self, 
        socket  = None, 
        name         : str = None, 
        tip          : str = "",
        panel        : str = "",
        user_label   : str = None,
        **props):
    """

    Parameters
    ----------
    socket : NodeSocket, optional
        the output socket to wrap default=None.

    name : str, optional
        input name if not None default=None.

    tip : str, optional
        description default="".

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

    user_label : str, optional
        user label default=None.

    """

    # ---------------------------------------------------------------------------
    # Attributes
    # ---------------------------------------------------------------------------

    self._layout      = None
    self._use_layout  = True
    self._tree        = Tree.current_tree()
    if self._tree is not None and not self._tree._rebuild:
        raise Break()
    self._bsocket     = None

    self._reset()

    # ---------------------------------------------------------------------------
    # Socket is a Node
    # ---------------------------------------------------------------------------

    if isinstance(socket, Node):
        socket = socket._out

    # ---------------------------------------------------------------------------
    # Empty socket
    # ---------------------------------------------------------------------------

    if utils.request_empty(socket):
        return

    # ---------------------------------------------------------------------------
    # Socket is a string or a String socket
    # ---------------------------------------------------------------------------

    socktype = self._socket_type
    cname = socktype.class_name

    if socktype.is_attribute:
        # Literal color names remain constants; String sockets name attributes.
        if ((isinstance(socket, str) and cname != 'Color') or
                (isinstance(socket, Socket) and socket.SOCKET_TYPE == 'STRING')):
            self._bsocket = self.Named(socket)._bsocket
            return

    # ---------------------------------------------------------------------------
    # Let's get the socket
    # ---------------------------------------------------------------------------

    self._bsocket = utils.get_bsocket(socket)
    if self._bsocket is not None:

        if self._bsocket.type != self.SOCKET_TYPE:

            # "Bundle Get Item" like nodes : we change the data_type
            node = self.node

            blid = node._bnode.bl_idname
            if blid == 'NodeGetBundleItem'and self.SOCKET_TYPE in utils.get_node_param_enum(blid, 'socket_type'):
                node._bnode.socket_type = self.SOCKET_TYPE
                self._bsocket = utils.get_enabled_bsocket(node, 'Item')

        return

    # ---------------------------------------------------------------------------
    # No name: we create from a constant Node
    # The socket argument is the value to set
    # ---------------------------------------------------------------------------

    if name is None:
        if socktype == 'GEOMETRY':
            new_socket = self.Input(None, halt=False)
            if new_socket is None:
                new_socket = self.NewInput(type(self).__name__)
            self._bsocket = new_socket._bsocket
        else:
            self._bsocket = self.Constant(socket, user_label=user_label)._bsocket

    # ---------------------------------------------------------------------------
    # With a name, we request the creation from current input
    # ---------------------------------------------------------------------------

    else:
        # Font : make sure it is a font 
        if self.SOCKET_TYPE == 'FONT':
            socket = blender.get_font(socket)

        # Socket can be the default value
        if socket is not None:

            if 'default' not in constants.SOCKETS[self._socket_type.type]['props']:
                raise NodeError(f"The {self._socket_type()} socket doesn't accept default value. <{socket}> is not valid.")

            # Perhaps it is given in the props
            def_key = 'default' if 'default' in props else None
            if def_key is None:
                def_key = 'default_value' if 'default_value' in props else None

            if def_key is None:
                props = {'value': socket, **props}

        new_socket = self.NewInput(name, tip=tip, panel=panel, **props)
        self._bsocket = new_socket._bsocket
        self._use_layout = new_socket._use_layout

_get_bsocket_from_input(name=None)

Get the availble input socket if any.

The socket is get a an OUTPUT socket of the current input.

Parameters:

Name Type Description Default
name str

name filter default=None.

None

Returns:

Type Description
Socket

or None if not found

Source code in core/socket_class.py
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
def _get_bsocket_from_input(self, name: str = None) -> bpy.types.NodeSocket:
    """ Get the availble input socket if any.

    The socket is get a an OUTPUT socket of the current input.

    Parameters
    ----------
    name : str, optional
        name filter default=None.


    Returns
    -------
    Socket
        or None if not found

    """
    in_node = self._tree.get_input_node()

    include = None if name is None else [name]

    bsockets = in_node.get_sockets('OUTPUT', include=include)
    for _, bsock in bsockets:
        if SocketType(bsock).type == self.SOCKET_TYPE:
            return bsock._bsocket
    else:
        return None

_jump(socket, reset=True)

Change the wrapped output socket

When changing the socket, the description is copied to the new socket. The node color, if any, is also propagated.

Parameters:

Name Type Description Default
socket NodeSocket

the new output socket to jump to

required
reset bool

reset the cache default=True.

True

Returns:

Type Description
self
Source code in core/socket_class.py
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
def _jump(self, socket: bpy.types.NodeSocket, reset: bool = True):
    """ Change the wrapped output socket

    When changing the socket, the description is copied to the new socket.
    The node color, if any, is also propagated.

    Parameters
    ----------
    socket : bpy.types.NodeSocket
        the new output socket to jump to

    reset : bool, optional
        reset the cache default=True.


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

    # Keep user label stored in socket description
    user_label = self.user_label

    bsocket = utils.get_bsocket(socket)
    if bsocket is None:
        raise NodeError(f"Socket error: Impossible to jump to socket {socket}")

    self._bsocket = bsocket
    if reset:
        self._reset()

    # Restore user label
    self.user_label = user_label

    return self

_lc(label=None, color=None)

Set node label and color.

This method returns self to be chained to as socket:

with GeoNodes("Node label and color"):
    Geometry().out()

    a = Float(10)._lc("Var a")
    b = Float(10)._lc("Var b")
    c = (a + b)._lc("a + b", (1, 0, 0))

Parameters:

Name Type Description Default
label str

node label default=None.

None
color SysColor

node color default=None.

None

Returns:

Type Description
self
Source code in core/socket_class.py
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
def _lc(self, label: str = None, color: SysColor = None):
    """ Set node label and color.

    This method returns self to be chained to as socket:

    ``` python
    with GeoNodes("Node label and color"):
        Geometry().out()

        a = Float(10)._lc("Var a")
        b = Float(10)._lc("Var b")
        c = (a + b)._lc("a + b", (1, 0, 0))
    ```

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

    color : SysColor, optional
        node color default=None.


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

    if self.node._bnode.bl_idname == 'NodeGroupInput':
        return self

    self.node_label = label
    self.node_color = color
    self.user_label = label

    return self

_ul(label)

Set the user label

Parameters:

Name Type Description Default
label str

the label to append

required

Returns:

Type Description
self
Source code in core/socket_class.py
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
def _ul(self, label : str):
    """ Set the user label

    Parameters
    ----------
    label : str
        the label to append


    Returns
    -------
    self
    """
    self.user_label = label
    return self

add_method(name=None, jump=False, ret_class=None, **fixed)

Add the current tree as a method of the Socket class.

Important

The socket instance must be an input socket of the Tree. This input plays the role of self argument.

with GeoNodes("Translate"):
    geo = Geometry()
    v = Vector(0, "Translation)
    geo.transform(translation=v)

    geo.add_method(jump=True)

Once the modifier completed, it can be called as a method of geometry geo.translate(translation=(1, 2, 3))

Parameters:

Name Type Description Default
name str

replace the default name which is the snake case version of the group name default=None.

None
ret_class type

transtype the default node output default=None.

None
jump bool

the calling socket jumps to the node outpus after the call default=False.

False
ret_class type

transtype the result with this class if not None default=None.

None
Source code in core/socket_class.py
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
def add_method(self, name: str = None, jump: bool = False, ret_class: type = None, **fixed):
    """ Add the current tree as a method of the Socket class.

    !!! important

        The socket instance must be an input socket of the Tree. This input plays the role of
        self argument.

    ``` python
    with GeoNodes("Translate"):
        geo = Geometry()
        v = Vector(0, "Translation)
        geo.transform(translation=v)

        geo.add_method(jump=True)
    ```

    Once the modifier completed, it can be called as a method of geometry ```geo.translate(translation=(1, 2, 3))```

    Parameters
    ----------
    name : str, optional
        replace the default name which is the snake case version of the group name default=None.

    ret_class : type, optional
        transtype the default node output default=None.

    jump : bool, optional
        the calling socket jumps to the node outpus after the call default=False.

    ret_class : type, optional
        transtype the result with this class if not None default=None.

    """

    if self.node._bnode.bl_idname != 'NodeGroupInput':
        raise NodeError(
            f"'add_method' can be called only from a 'Group Input' socket. "
            "This socket is used a 'self' argument when calling the method of {type(self).__name__}.")

    tree = Tree.current_tree()

    # ---------------------------------------------------------------------------
    # Method Body
    # ---------------------------------------------------------------------------

    socket_rank = self.node._outputs.get_socket_rank(self)
    socket_name = utils.snake_case(self._bsocket.name)


    def call(self_, *args, **kwargs):
        node = Group(tree._btree.name)
        if socket_rank >= len(args):
            new_args = args
            new_kwargs = {socket_name: self_, **kwargs}
        else:
            new_args = args[:socket_rank] + (self_,) + args[socket_rank:]
            new_kwargs = kwargs

        res = node.method_call(*new_args, ret_class=ret_class, **new_kwargs, **fixed)

        if jump:
            return self_._jump(res)
        else:
            return res

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

    if name is None:
        name = tree._btree.name[len(tree._prefix):].strip()
        name = utils.snake_case(name)

    class_ = type(self)
    if name in dir(class_):
        print(f"CAUTION: the method '{name}' (implementing group '{tree._btree.name}') already exists in class {class_}.")

    setattr(class_, name, call)

field_to_list(count, **values)

Node Field to List

Create a list from this field and named lists from additional fields.

Parameters:

Name Type Description Default
count Integer

Number of items in each generated list.

required
values dict

Named fields to evaluate. Each field creates an output socket with the same name.

{}

Returns:

Type Description
Socket

First list output. The other outputs are available from its node or as peer sockets.

Source code in core/socket_class.py
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
def field_to_list(self, count, **values):
    """ > Node Field to List

    Create a list from this field and named lists from additional fields.

    Parameters
    ----------
    count : Integer
        Number of items in each generated list.

    values : dict
        Named fields to evaluate. Each field creates an output socket with
        the same name.

    Returns
    -------
    Socket
        First list output. The other outputs are available from its node
        or as peer sockets.
    """
    return Node(
        'Field to List',
        named_sockets={self._name: self},
        count=count,
        **values,
    )._out

flatten_list()

Flatten one level of a rectangular nested list.

Every nested list must have the same length. This is notably the case for lists created by :meth:reshape_list. Items keep their original linear order.

values = Float.List(*range(16))
values.reshape_list((4, 4))
values.flatten_list()

Returns:

Type Description
Socket

This socket, updated to point to the flattened list.

Raises:

Type Description
NodeError

If this socket does not contain a list.

Source code in core/socket_class.py
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
def flatten_list(self):
    """Flatten one level of a rectangular nested list.

    Every nested list must have the same length. This is notably the case
    for lists created by :meth:`reshape_list`. Items keep their original
    linear order.

    ``` python
    values = Float.List(*range(16))
    values.reshape_list((4, 4))
    values.flatten_list()
    ```

    Returns
    -------
    Socket
        This socket, updated to point to the flattened list.

    Raises
    ------
    NodeError
        If this socket does not contain a list.
    """

    if not self._is_list:
        raise NodeError(f"Socket.flatten_list error: {self} is not a list.")

    from .sock_closure import Closure
    from .sock_integer import Integer

    with Layout("Socket.flatten_list"):

        source = self
        outer_length = source.list_length()
        inner_length = source[0].list_length()

        with Closure() as cl:
            index = Integer(0, "Index")

            outer_index = index // inner_length
            inner_index = index % inner_length

            source[outer_index][inner_index].out(self._name)

        self._jump(cl.to_list(outer_length * inner_length))
        return self

index_switch(*values, index=None, default_index=0)

Node Index Switch

with GeoNodes("index_switch demo") as tree:

    # Create some geometries
    geo    = Geometry()
    cube   = Mesh.Cube()
    sphere = Mesh.IcoSphere()
    cone   = Mesh.Cone()

    # Pick in this list
    pick_geo = geo.index_switch(cube, sphere, cone, index=tree.new_input("Geometry index", default_value=2))

    # Plug the result to the output
    pick_geo.out()

Parameters:

Name Type Description Default
*values Any

List of Sockets to select into

()
index Integer

socket 'Index' (Index)

None
default_index int

default idex

0

Returns:

Type Description
Socket
Source code in core/socket_class.py
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
def index_switch(self, *values, index = None, default_index: int = 0):
    """ > Node Index Switch

    ``` python
    with GeoNodes("index_switch demo") as tree:

        # Create some geometries
        geo    = Geometry()
        cube   = Mesh.Cube()
        sphere = Mesh.IcoSphere()
        cone   = Mesh.Cone()

        # Pick in this list
        pick_geo = geo.index_switch(cube, sphere, cone, index=tree.new_input("Geometry index", default_value=2))

        # Plug the result to the output
        pick_geo.out()
    ```

    Parameters
    ----------
    *values : Any
        List of Sockets to select into

    index : Integer, optional
        socket 'Index' (Index)

    default_index : int, default=0
        default idex

    Returns
    -------
    Socket
    """
    return self.IndexSwitch(self, *values, index=index, default_index=default_index)

Link input sockets of the node

Allow to chain input sockets linking.

Source code in core/socket_class.py
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
def link_inputs(self,
    from_node   : Node = None,
    from_panel  : str = "",
    *,
    include     : list =  None,
    exclude     : list  = [],
    panel       : str = "",
    ):
    """ Link input sockets of the node

    Allow to chain input sockets linking.
    """
    self.node.link_inputs(from_node, from_panel=from_panel, include=include, exclude=exclude, panel=panel)
    return self

Link panel input sockets of the node

Allow to chain input sockets linking.

Source code in core/socket_class.py
1421
1422
1423
1424
1425
1426
1427
def link_panel(self, panel: str, from_node : Node = None):
    """ Link panel input sockets of the node

    Allow to chain input sockets linking.
    """
    self.node.link_panel(panel, from_node=from_node)
    return self

list_append(value)

Append a value or another list to this list.

If value is a list socket, all its items are appended. Otherwise, value is converted to the socket type and appended as one item. The socket is updated in place to point to the resulting list.

values = Float.List(1, 2, 3)
values.list_append(4)

other = Float.List(5, 6)
values.list_append(other)

Parameters:

Name Type Description Default
value Any | Socket

Single value or list socket to append.

required

Returns:

Type Description
Socket

This socket, updated to point to the concatenated list.

Raises:

Type Description
NodeError

If this socket does not contain a list.

Source code in core/socket_class.py
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
def list_append(self, value):
    """Append a value or another list to this list.

    If ``value`` is a list socket, all its items are appended. Otherwise,
    ``value`` is converted to the socket type and appended as one item.
    The socket is updated in place to point to the resulting list.

    ``` python
    values = Float.List(1, 2, 3)
    values.list_append(4)

    other = Float.List(5, 6)
    values.list_append(other)
    ```

    Parameters
    ----------
    value : Any | Socket
        Single value or list socket to append.

    Returns
    -------
    Socket
        This socket, updated to point to the concatenated list.

    Raises
    ------
    NodeError
        If this socket does not contain a list.
    """

    from .sock_closure import Closure
    from .sock_integer import Integer

    if not self._is_list:
        raise NodeError(f"Socket.list_append error: {self} is not a list.")

    with Layout("Socket.list_append"):

        # Turn the appended value into a closure indexed from zero.
        in_cl = None
        if isinstance(value, Socket) and value._is_list:
            n = value.list_length()
            with Closure() as cl:
                index = Integer(0, "Index")
                value[index].out("Value")
            in_cl = cl
        else:
            n = 1
            with Closure() as cl:
                index = Integer(0, "Index")
                type(self)(value).out("Value")
                index.out() # To avoid warning
            in_cl = cl

        cur_length = self.list_length()

        # Keep the current items first, then evaluate the appended value.
        with Closure() as cl:
            index = Integer(0, "Index")

            v = type(self).Switch(index.less_than(cur_length), 
                    in_cl.evaluate(index=index-cur_length).value,
                    self[index]
                    )
            v.out(self._name)

        # Replace the wrapped socket while preserving its Python identity.
        return self._jump(cl.to_list(cur_length + n))

menu_switch(self_name='Self', named_sockets={}, default_menu=None, **sockets)

Node Menu Switch

[&NO_JUMP]

Self is connected to the first menu item with the name provided as argument.

The items of the Menu Switch node are provided in the 'items' dict. An group input socket named after the 'name' argument is linked to menu selector.

Parameters:

Name Type Description Default
named_sockets dict

sockets to create default={}.

{}
default_menu str

default menu value default=None.

None
sockets dict

items

{}

Returns:

Type Description
Socket
Source code in core/socket_class.py
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
def menu_switch(self,
            self_name       : str = 'Self', 
            named_sockets   : dict = {},
            default_menu    : str = None,
            **sockets):
    """ > Node Menu Switch

    [&NO_JUMP]

    Self is connected to the first menu item with the name provided as argument.

    The items of the Menu Switch node are provided in the 'items' dict.
    An group input socket named after the 'name' argument is linked to menu selector.

    Parameters
    ----------
    named_sockets : dict, optional
        sockets to create default={}.

    default_menu : str, optional
        default menu value default=None.

    sockets : dict
        items


    Returns
    -------
    Socket
    """        
    return self.MenuSwitch(named_sockets = {self_name: self, **named_sockets}, default_menu=default_menu, **sockets)

out(name=None, panel='', **props)

Plug the value to the Group Output Node.

with GeoNodes("Plug to group output"):
    # Create a cube
    geo = Mesh.Cube()
    # To Group Output geometry as socket named "Cube"
    geo.out("Cube")

The "Do nothing" modifier is simply Geometry().out()

Parameters:

Name Type Description Default
name str

socket name default=None.

None

Returns:

Type Description
None
Source code in core/socket_class.py
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
def out(self, name: str = None, panel: str = "", **props):
    """ Plug the value to the Group Output Node.

    ``` python
    with GeoNodes("Plug to group output"):
        # Create a cube
        geo = Mesh.Cube()
        # To Group Output geometry as socket named "Cube"
        geo.out("Cube")
    ```

    The "Do nothing" modifier is simply ``` Geometry().out() ```

    Parameters
    ----------
    name : str, optional
        socket name default=None.


    Returns
    -------
    None
    """
    self._is_empty(f"Impossible to link an empty socket (name: '{name}').")

    out_node = self._tree.get_output_node()
    out_node.set_input_socket(name=name, value=self, create=True, panel=panel, **props)

repeat(iterations=1, named_sockets={}, **sockets)

Repeat zone

Parameters:

Name Type Description Default
iterations Integer

iteration socket

1
named_sockets dict

named sockets

{}
sockets dict

other sockets

{}

Returns:

Type Description
ZoneIterator
Source code in core/socket_class.py
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
def repeat(self, iterations=1, named_sockets: dict={}, **sockets):
    """ Repeat zone

    Parameters
    ----------
    iterations : Integer, default=1
        iteration socket

    named_sockets : dict, default={}
        named sockets

    sockets : dict, optional
        other sockets


    Returns
    -------
    ZoneIterator
    """
    class_name = type(self).__name__
    node = ZoneNode("Repeat", named_sockets={class_name: self, **named_sockets}, Iterations=iterations, **sockets)
    return ZoneIterator(self, node)

reshape_list(shape)

Reshape a flat list into nested lists.

shape defines the length of each list level. Items keep their original linear order.

values = Float.List(*range(16))
matrix = values.reshape_list((4, 4))

first  = matrix[0][0]
last   = matrix[3][3]

Shapes with more than two dimensions are supported:

values = Float.List(*range(24))
blocks = values.reshape_list((2, 3, 4))

Dimensions can also be Integer sockets:

rows = Integer(name="Rows")
table = values.reshape_list((rows, 4))

A single dimension does not require a tuple:

values.reshape_list(16)
# Equivalent to values.reshape_list((16,))

A one-dimensional shape flattens one existing level of nested lists. A warning is emitted when the resulting length differs from the requested dimension.

Parameters:

Name Type Description Default
shape int | Integer | tuple[int | Integer]

Length of every dimension. A single integer is interpreted as a one-dimensional shape. Dimensions must be strictly positive.

required

Returns:

Type Description
Socket

This socket, updated to point to the reshaped list.

Source code in core/socket_class.py
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
def reshape_list(self, shape):
    """Reshape a flat list into nested lists.

    ``shape`` defines the length of each list level. Items keep their
    original linear order.

    ``` python
    values = Float.List(*range(16))
    matrix = values.reshape_list((4, 4))

    first  = matrix[0][0]
    last   = matrix[3][3]
    ```

    Shapes with more than two dimensions are supported:

    ``` python
    values = Float.List(*range(24))
    blocks = values.reshape_list((2, 3, 4))
    ```

    Dimensions can also be Integer sockets:

    ``` python
    rows = Integer(name="Rows")
    table = values.reshape_list((rows, 4))
    ```

    A single dimension does not require a tuple:

    ``` python
    values.reshape_list(16)
    # Equivalent to values.reshape_list((16,))
    ```

    A one-dimensional shape flattens one existing level of nested lists.
    A warning is emitted when the resulting length differs from the
    requested dimension.

    Parameters
    ----------
    shape : int | Integer | tuple[int | Integer]
        Length of every dimension. A single integer is interpreted as a
        one-dimensional shape. Dimensions must be strictly positive.

    Returns
    -------
    Socket
        This socket, updated to point to the reshaped list.

    """

    if not hasattr(shape, '__len__'):
        shape = (shape,)

    shape = tuple(shape)

    ok_shape = True
    for d in shape:
        if isinstance(d, Socket):
            oK_shape = False

    shape_str = f"({shape})" if ok_shape else ""

    from .sock_closure import Closure
    from .sock_integer import Integer
    from .sock_string import String

    with Layout(f"Socket.reshape_list{shape_str}"):

        if len(shape) == 1:

            self.flatten_list()

            res_length = self.list_length()

            message = String.Join(
                f"{self._name}.reshape_list(" + Integer(shape[0]).to_string() + ")",
                "the resulting list length is",
                res_length.to_string(),
                delimiter = " ",
            )

            self.list_length().not_equal(shape[0]).warning(message)
            return self

        dimensions = [Integer(size) for size in shape]

        # ----- Build nested lists

        def build(level, linear_index=None):
            with Closure() as closure:
                index = Integer(0, "Index")

                if linear_index is None:
                    next_index = index
                else:
                    next_index = linear_index * dimensions[level] + index

                if level == len(dimensions) - 1:
                    value = self[next_index]
                else:
                    value = build(level + 1, next_index)

                value.out("Value")

            return closure.to_list(count=dimensions[level])

        self._jump(build(0))
        return self

simulation(named_sockets={}, **sockets)

Simulation zone

Parameters:

Name Type Description Default
named_sockets dict

named sockets

{}
sockets dict

other sockets

{}

Returns:

Type Description
ZoneIterator
Source code in core/socket_class.py
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
def simulation(self, named_sockets: dict={}, **sockets):
    """ Simulation zone

    Parameters
    ----------
    named_sockets : dict, default={}
        named sockets

    sockets : dict, optional
        other sockets

    Returns
    -------
    ZoneIterator
    """
    class_name = type(self).__name__
    node = ZoneNode("Simulation", named_sockets={class_name: self, **named_sockets}, **sockets)
    return ZoneIterator(self, node)

switch(condition=None, true=None)

Node Switch

Self is connected to 'false' socket.

Note

switch returns self if global constant SWITCH_JUMP = True (default) set SWITCH_JUMP = False for legacy behavior

with GeoNodes("Switch demo"):

    from geonodes import core_module
    constants = core_module.constants
    # Legacy behavior (default is True)
    constants.SWITCH_JUMP = False

    choice = Boolean(True, "Use Sphere")

    # Two possible geometries
    cube   = Mesh.Cube()
    sphere = Mesh.IcoSphere()

    # Select
    # Legacy behavior: cube is unchanged otherwise cube
    geo = cube.switch(choice, sphere)

    # To group output
    geo.out()
Information
  • Socket 'False' : self

Parameters:

Name Type Description Default
condition Boolean

socket 'Switch' (Switch)

None
true

socket 'True' (True)

None

Returns:

Type Description
Socket(self)
Source code in core/socket_class.py
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
def switch(self, condition=None, true=None):
    """ > Node Switch

    Self is connected to 'false' socket.

    !!! note
        switch returns self if global constant SWITCH_JUMP = True (default)
        set SWITCH_JUMP = False for legacy behavior

    ``` python
    with GeoNodes("Switch demo"):

        from geonodes import core_module
        constants = core_module.constants
        # Legacy behavior (default is True)
        constants.SWITCH_JUMP = False

        choice = Boolean(True, "Use Sphere")

        # Two possible geometries
        cube   = Mesh.Cube()
        sphere = Mesh.IcoSphere()

        # Select
        # Legacy behavior: cube is unchanged otherwise cube
        geo = cube.switch(choice, sphere)

        # To group output
        geo.out()
    ```

    Information
    -----------
    - Socket 'False' : self

    Parameters
    ----------
    condition : Boolean
        socket 'Switch' (Switch)

    true
        socket 'True' (True)


    Returns
    -------
    Socket (self)
    """
    res = self.Switch(condition=condition, false=self, true=true)
    if constants.SWITCH_JUMP:
        return self._jump(res)
    else:
        return res

switch_false(condition=None, false=None)

Node Switch

[&JUMP]

Self is connected to 'true' socket.

Important

This methods behaves the inverse of switch : self is connected to "True" socket and the argument to "False", socket

Note

This method is mainly provided to cover the case when 'False' socket is None

with GeoNodes("Switch demo"):

    geo = Geometry()

    show_geometry = Boolean(False, "Merge with Cube")

    cube = Mesh.Cube()

    geo += cube.switch_false(show_geometry)

    # Is equivalent to
    geo += Geometry.Switch(show_geometry, None, cube)

    # To group output
    geo.out()

Note

This method let self socket unchanged. To set self socket to the result

Information
  • Socket 'True' : self

Parameters:

Name Type Description Default
condition Boolean

socket 'Switch' (Switch)

None
false

socket 'False' (False)

None

Returns:

Type Description
Socket
Source code in core/socket_class.py
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
def switch_false(self, condition=None, false=None):
    """ > Node Switch

    [&JUMP]

    Self is connected to 'true' socket.

    !!! important
        This methods behaves the inverse of switch : self is connected to "True" socket and  the argument to "False", socket

    !!! note
        This method is mainly provided to cover the case when 'False' socket is None

    ``` python
    with GeoNodes("Switch demo"):

        geo = Geometry()

        show_geometry = Boolean(False, "Merge with Cube")

        cube = Mesh.Cube()

        geo += cube.switch_false(show_geometry)

        # Is equivalent to
        geo += Geometry.Switch(show_geometry, None, cube)

        # To group output
        geo.out()
    ```

    !!! note
        This method let self socket unchanged. To set self socket to the result

    Information
    -----------
    - Socket 'True' : self

    Parameters
    ----------
    condition : Boolean
        socket 'Switch' (Switch)

    false
        socket 'False' (False)


    Returns
    -------
    Socket
    """
    res = self.Switch(condition=condition, false=false, true=self)
    if constants.SWITCH_JUMP:
        return self._jump(res)
    else:
        return res

to_list(count=None)

Node Field to List

Shortcut for self.field_to_list(count) when only this field has to be converted to a list.

Parameters:

Name Type Description Default
count Integer

Number of items in the generated list.

None

Returns:

Type Description
Socket

List containing the values obtained by evaluating this field.

Source code in core/socket_class.py
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
def to_list(self, count=None):
    """ > Node Field to List

    Shortcut for ``self.field_to_list(count)`` when only this field has
    to be converted to a list.

    Parameters
    ----------
    count : Integer, optional
        Number of items in the generated list.

    Returns
    -------
    Socket
        List containing the values obtained by evaluating this field.
    """
    return Node('Field to List', named_sockets={self._name: self}, count=count)._out

to_node_inputs(node, *names)

Connect successive list items to a node's inputs.

This is the natural socket-oriented shortcut for node._list_to_inputs(*names, socket_list=self).

When names is empty, all node inputs matching the type of the list items are fed, in their order on the node. Otherwise, only the named inputs are used.

separate = Node('Separate XYZ', vector=vector)
components = separate._outputs_to_list()

combine = Node('Combine XYZ')
components.to_node_inputs(combine)

Parameters:

Name Type Description Default
node Node

Node whose inputs are to be connected.

required
names str

Optional names of the inputs to feed.

()

Returns:

Type Description
Node

The target node.

Source code in core/socket_class.py
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
def to_node_inputs(self, node, *names):
    """Connect successive list items to a node's inputs.

    This is the natural socket-oriented shortcut for
    ``node._list_to_inputs(*names, socket_list=self)``.

    When ``names`` is empty, all node inputs matching the type of the list
    items are fed, in their order on the node. Otherwise, only the named
    inputs are used.

    ``` python
    separate = Node('Separate XYZ', vector=vector)
    components = separate._outputs_to_list()

    combine = Node('Combine XYZ')
    components.to_node_inputs(combine)
    ```

    Parameters
    ----------
    node : Node
        Node whose inputs are to be connected.

    names : str
        Optional names of the inputs to feed.

    Returns
    -------
    Node
        The target node.
    """
    return node._list_to_inputs(*names, socket_list=self)