Create a node group from an existing node tree

I have a node tree that I want to move into a node group. The only ways I’ve found to do that is with bpy.ops.node.group_make or by adding every node individually, connecting them and setting all parameters.
The second option isn’t that great so I’m using the operator.

This works perfectly if I run it in the node editor, but I need to run it from a button in the properties panel. I couldn’t find any good way to do this so I ended up trying to switch the context temporarily. So basically I just set context.area.type = "NODE_EDITOR"

Because that gave an incorrect context error I decided to take a look at the source code. I’m not at all familiar with it and I don’t even really know C, but what I got from it was that it isn’t just looking for the area type but also if space.edit_tree is set.

To me it seems like the issue here is that when I run area.type = "NODE_EDITOR" the edit_tree attribute is None until the operator has finished running which is why the poll is failing.

At this point it seems like there should be a better way to do this, but I’m not familiar with any way of solving this.
Does anyone know how to solve the problem with edit_tree being None or even better a good way of creating a node group from an existing tree?

1 Like

I’m reposting this answer as I had problems with my account the last time I responded to this, deleted that account but the answer also went.

active_area = context.area
active_area_type = active_area.type
active_area.type = "NODE_EDITOR"
active_area.ui_type = "ShaderNodeTree"
context.space_data.node_tree = your_tree_name
bpy.ops.node.group_make()
active_area.type = active_area_type