Python: Add existing NodeGroup to Material My goal is to add a NodeGroup I created earlier to the shader nodetree of an object using python. (Actually a few hundred times, hence the script)

This is what I know how to do:


iterate over all the objects of which I need to change the Material.


Here is where I get stuck:


I can add a new NodeGroup with object.data.materials[0].node_tree.nodes.new("ShaderNodeGroup")
This only creates a generic NodeGroup and I'm unable to select the actual Nodetree within this new Group.
py.ops.node.add_node(type="ShaderNodeGroup", use_transform=True, settings=[{"name":"node_tree", "value":"bpy.data.node_groups['MyNodeGroup']"}]) is the operator to add the Nodegroup that I want, but when I try to use that in my script, I get an error that I'm in the wrong context.


How can I make any of these methods work for my script?
You can do something like this: create the node group instance and set the existing node group as node tree for this new instance.
import bpy

C = bpy.context

def instantiate_group(nodes, data_block_name):
    group = nodes.new(type='ShaderNodeGroup')
    group.node_tree = bpy.data.node_groups[data_block_name]
    return group

instantiate_group(C.object.material_slots[0].material.node_tree.nodes, 'NodeGroup')