Can somebody explain to me how bpy.ops work?
Does it always need to define active objects before calling ops module on them?
Here is what is bothering me. I have two materials in blend file. I would like to copy all nodes from one material, and then clear nodes in other material and paste copied nodes from clipboard.
I have found a way to do that via defining active objects with corresponding materials, and then calling bpy.ops on them.
But I was wondering can this be done without defining active objects first? Just work on a material level?
Most operators rely on the context in which they’re executed to determine what they’re operating on.
Context can be overridden with a dictionary, but it’s not always clear what the required context is and you may need to check the Blender source (or guess using trial and error). https://docs.blender.org/api/current/bpy.ops.html#overriding-context
In general, I personally avoid operators whenever possible as they’re slow to execute and the reliance on context is awkward. But, if you’re not confident with Python and reading the bpy documentation, you may be better served by sticking to them for now.
When I run this code first time it gives me error on bpy.ops.node.select_all part saying the context is incorrect, but when I run it immediately after that it runs without error and it works like it should. Why is this happening?
Not by ‘copy and pasting’, but yes you could loop through the nodes and their links to recreate them in a different node tree. In my experience there are very few things you need to use operators for.
Because the context is different and you’re not overriding it. Don’t edit the context, create an override as demonstrated in the documentation I previously linked.