Excluding all collections from view layer using script

Hello Im working on really big project and I need to exclude all collections from view layer and reverse using script I tried this

import bpy

coll = bpy.data.collections
for c in coll:
   c.exclude = False

But it doesnt seem to work, any ideas where it went wrong or how to solve my problem? Any help is appreciated.

You need to use refence from view_layer.layer_collection:

import bpy
vl_colls = bpy.context.view_layer.layer_collection.children

# toggle
for coll in vl_colls:
    coll.exclude = not coll.exclude

Layer collection vs Collection:



Properties of LayerCollection(bpy_struct):

layercoll props

  • Exclude
  • Hide in Viewport
  • Holdout
  • Indirect Only

Accessed through bpy.context.view_layer.layer_collection.children

Properties of Collection(ID):

coll props

  • Disable Selection
  • Disable in Viewport
  • Disable in Render

Accessed through bpy.data.collections


If you want to also exclude grand-children and grand-grand-children etc you’ll have to traverse the tree, begginning with the leaf children and working your way up :

def get_all_children(col):
    yield col
    for child in col.children:
        yield from get_all_children(child)

view_layer = bpy.context.view_layer
for layer_col in reversed(list(get_all_children(view_layer.layer_collection))):
    layer_col.exclude = True

Another method that doesn’t use recursion. Python has a limit that depends on a number of factors that prevents calling recursively the same function more than a certain amount of times. You shouldn’t reach it in a regular workflow but, if it ever happens.

layer_collections = [bpy.context.view_layer.layer_collection]
while layer_collections:
    l_c = layer_collections.pop(0)
    l_c.exclude = True