# How to get the end node of a tree in python?

From a given node tree, what is the most reliable way to get the end node being used for output, if any?

My current approach is to check for the correct output type for the tree (OUTPUT_MATERIAL, OUTPUT_WORLD...) and for is_active_output:

nodes = node_tree.nodes

for n in nodes:
if n.type == 'OUTPUT_WORLD' and n.is_active_output:
return n

return None


However, I see no guarantee that there is only one node with is_active_output (I can set this to True in multiple nodes).

The ShaderNodeTree has an active_input field, but the value is -1.

I have experimented with it and this is what i come up with :

• The active_output is not a node type so it will not contain the active output node, it is NodeSocketInterface ( i don't know what this is )

• as you have found you can set multiple nodes is_active_output to true and this will be misleading, but apparently this is handled automatically by blender like this : the last selected output node (in the UI ) is set to be the active output and all other output nodes get their is_active_output property cleared.

• if you set is_active_output to True for multiple nodes the first one in the node_tree.nodes list is the active one.
• if you clear the is_active_output of all nodes then the first output node in the list node_tree.nodes is the active one.

to handle this in code i have two functions to get/set the active output :

def set_active(my_node):
nodes = my_node.id_data.nodes
for node in nodes :
if node.type == 'OUTPUT_MATERIAL' :
node.is_active_output = False
my_node.is_active_output = True

def get_active(nodes):
for node in nodes :
if node.type == 'OUTPUT_MATERIAL' and node.is_active_output :
return node
for node in nodes :
if node.type == 'OUTPUT_MATERIAL' :
return node

• thank you for taking the trouble of experimenting and providing a very complete answer – brita_ May 3 '15 at 19:03
• you are welcome , I got curious and couldn't stop : ) – Chebhou May 3 '15 at 19:10