Trouble understanding context for bpy.ops.node.group_ungroup()


I was wondering if anyone had any insights into this problem (as it’s driving me insane :slightly_frowning_face:…)

I’ve done my best to describe it. Sorry if it’s a bit long, and let me know if you need clarification.

Background / Overall Goal

I have a script that runs from the render context of the properties panel. This script cycles through the materials of objects selected in the 3D View, and “fiddles” with the nodes.

Simply put - I want to ungroup all node groups each material.

The Problem

As best I can tell, there doesn’t seem to be a way to ungroup node groups via The only solution would seem to be copying each node from the node group node_tree to the material node_tree one by one and recreating the links. This seems like a nightmare.

So, instead I turn to bpy.ops.node.group_ungroup() - but I cannot get this to run consistently. See the next heading.

Issues with bpy.ops.node.group_ungroup()

Consider this proof of concept code. Assume the node group in question is already selected and active:

import bpy
#Store where we started
home_area = bpy.context.area.type
home_ui = bpy.context.area.ui_type

#Change context so that bpy.ops.node.group_ungroup() will work
bpy.context.area.type = “NODE_EDITOR”
bpy.context.area.ui_type = “ShaderNodeTree”
bpy.context.space_data.shader_type = “OBJECT”

#Restore where we started from
bpy.context.area.type = home_area
bpy.context.area.ui_type = home_ui

If I open Blender and input that code into the text editor and hit run, it works! :slight_smile: The selected node group is ungrouped.

If I put that code into my existing script (the one mentioned above, that runs from the render context of the properties panel) it fails :frowning:

The properties panel is changed into the NODE_EDITOR, but then the script crashes with “context is incorrect” for bpy.ops.node.group_ungroup()

It leaves my properties panel in the node_editor view.

And even weirder

After it crashes, if I simply change my the (now) node_editor panel back to the properties panel, and click the exact same button again, IT WORKS JUST FINE.


Clearly I am missing something about the required context for bpy.ops.node.group_ungroup().

How can it crash for context incorrect, and then run the second time I click the same button? Having changed nothing else.

Could it be something to do with my mouse position? The last part of the window that I clicked on?

What’s the secret?

1 Like

Because this is hard for me to describe, and because a YouTube video is worth a thousand words… here is a video depicting the issue.

I can’t understand this. You will see that the script fails the first time for context incorrect… and then works the second time for seemingly no reason.

Can anyone help me understand?