I'd like to get all materials using an ambient occlusion (AO) node and return their names in the console:

import bpy

mat = bpy.data.materials
for mat in mat:
    mat_name = (mat.name)
    ntree = mat.node_tree
    node = ntree.nodes.get("Ambient Occlusion", None)

    if node is not None:
        print("Material With Ambient Occlusion:", mat_name)

It works fine for the start up file, but when I run it in another scene I get this error:

AttributeError: 'NoneType' object has no attribute 'nodes'

What is wrong? And why does the code only work for the start up file?


1 Answer 1


Not all materials have an associated node_tree. This is only present where the 'use_nodes' checkbox has been used as this creates the node tree.

Your problem is that one or more material does not have a node_tree. The solution is to include a test before the ntree.nodes.get() to first check that there is actually an attribute 'nodes' - and to simply skip that material if none is found:

import bpy

# Run through all materials of the current blend file
for mat in bpy.data.materials:
    # If the material has a node tree
    if mat.node_tree:
        # Run through all nodes
        for node in mat.node_tree.nodes:
            # If the node type is Ambient Occlusion 
            if node.type == 'AMBIENT_OCCLUSION':
                # Print the name of the material
                print("Ambient Occlusion Node found in:", mat.name)
  • 1
    $\begingroup$ Thanks to @brockmann for the great edit to improve clarity. $\endgroup$ Nov 20, 2020 at 16:34
  • 1
    $\begingroup$ Thank you!it's fixed! $\endgroup$ Nov 20, 2020 at 16:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .