Blender scripting connect nodes I'am beginner at python and blender. I' am trying to create simple addon for myself as part of learning process. I want to achieve that, if i run the script, mixrgb node is added to node tree and link to shader, and if i run script again another mixrgb node is added and linked to shader instead of previous one and previous one link to new one input. Here is the code
import bpy
nodes = bpy.context.active_object.active_material.node_tree.nodes
links = bpy.context.active_object.active_material.node_tree.links
mix = nodes.new('ShaderNodeMixRGB')


mix.location = (-300, -200)
mix.label = &quot;mix&quot;

for n in nodes :
    if n.label == &quot;mix&quot; :
    n.location.y -= 200
links.new(mix.outputs[0], nodes['Principled BSDF'].inputs[0])

Node is created and linked to shader, if i run the script again , new node is created and conected to shader ,previous one change its y location , and here i would like to link old node output to new node input.
I tried
links.new(mix.outputs[0] , mix.inputs[1])

But it conects to itself.
I dont want to make separate nodes like mixrgb2 mixrgb3, because i would like to be able to add infinite number of nodes , which are linked to previous.
If somebody can show me the correct way or creating that, iam stuck in that point for few days already. I was searching for solution here and every other forum, but no success, that 's why i decided to make a post.
Look for the link.

Each run of script, offsetting old mix node
's location.x

Put all current mix nodes into a list.
Find any links between a mix node and the principle shader
Make a new mix node.
If there's a link attach the from node (a mix node) output to the
input of new mix node
Make link new mix node to principled shader
Move the old mix nodes.  Could do this prior... sometimes handy to post-process incase a prior step is aborted.)

Test script
import bpy
context = bpy.context
nodes = context.active_object.active_material.node_tree.nodes
links = context.active_object.active_material.node_tree.links
ps = nodes.get('Principled BSDF')


mixnodes = [n for n in nodes if n.label == &quot;mix&quot;]
mix_ps_links = [l for l in links if l.from_node.label == &quot;mix&quot; and l.to_node == ps]

# add new mix node
mix = nodes.new('ShaderNodeMixRGB')
mix.location = (-300, -200)
mix.label = &quot;mix&quot;

if mix_ps_links:
    link = mix_ps_links.pop()
    links.new(link.from_node.outputs[0], mix.inputs[0])

links.new(mix.outputs[0], ps.inputs[0])

for mix in mixnodes:
    mix.location.y -= 200

Note: I use the line in test code context = bpy.context to make it cut and paste directly into methods where context is passed, eg def execute(self, context):