Add sockets to menuswitch geometry node

I’m trying to procedurally generate a list of menu options on a menuswitch geometry node. I’m able to create the node and modify the two default menu options but I need to add more options. This is possible via the geo node side panel ui, but I have many options and need to do this via python.

Here’s what I’ve go so far:

import bpy
node_tree = bpy.context.object.modifiers.get("GeometryNodes").node_group
menu_switch = node_tree.nodes.new("GeometryNodeMenuSwitch")
menu_switch.data_type = 'RGBA'
for i, (name, rgba) in enumerate(menu_options.items()):
    idx = i+1
    menu_switch.inputs[idx].name = name
    menu_switch.inputs[idx].default_value = rgba

This obviously breaks on the third input since there are only two by default. I tried adding a step to create new items like this:

    if idx > 2:
        menu_switch.inputs.new('RGBA', name, identifier=f'Item_{i}', default_value=rgba)

But that gave me:

Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
RuntimeError: Error: Cannot add socket to built-in node

Any ideas?

To add ‘options’ to a Menuswitch node, you need to change the enum_items collection. (sockets are then build automatically from the items in that collection)

if idx >= len(menu_switch.enum_items):
    menu_switch.enum_times.new(name)

You can create a node graph you need and then save it to Python code using https://extensions.blender.org/add-ons/node-to-python/ and then investigate the generated Python code to reuse it in your script.

Works great. Thanks!!

Great tip @Andrej - thanks!