# Default value for bpy.props.CollectionProperty

How to set a default value for bpy.props.CollectionProperty?

Let's use the example in the documentation for an answer.

I tried to set the default value in the register function, but neither bpy.data nor bpy.context is available at that moment.

• There is no default for a collection. By default the collection is empty when first defined. Sep 26, 2018 at 16:07
• Maybe there is a walk-around. I tried to set the default value in the register function, but neither bpy.data nor bpy.context is available at that moment. Sep 26, 2018 at 17:06
• Can you add to question what you want the default to be? From comment sounds like you want to add a default item on creation. One trick is to add a handler during rego that runs until one "default" item is added, then removes itself (the handler). Sep 27, 2018 at 12:06
• @batFINGER I've added a solution that worked for me as the answer Sep 27, 2018 at 23:45

The idea is to use application handlers to set the default value for bpy.props.CollectionProperty:

• bpy.app.handlers.scene_update_post to set the default value right after the addon registration via register() and then remove the handler
• bpy.app.handlers.load_post with @persistent decorator to set the default value after any of the following events:
• opening Blender
• reloading the start-up file via the keys Ctrl N
• opening any Blender file.

Here is the code:

import bpy
from bpy.app.handlers import persistent

class MyCollectionItem(bpy.types.PropertyGroup):
name = bpy.props.StringProperty(name="Name", default="Unknown")
value = bpy.props.StringProperty(name="Value", default="Unknown")

def setDefaultCollectionValue():
myCollection = bpy.context.scene.myCollection
# set default value if <myCollection> is empty
if not myCollection:
collectionItem.name = "Name 1"
collectionItem.value = "Value 1"
collectionItem.name = "Name 2"
collectionItem.value = "Value 2"

# This handler is needed to set the default value for <bpy.context.scene.myCollection>
# right after the addon registration via register()
def onRegister(scene):
setDefaultCollectionValue()
# the handler isn't needed anymore, so remove it
bpy.app.handlers.scene_update_post.remove(onRegister)

# This handler is needed to set the default value for <bpy.context.scene.myCollection>
# after any of the following events:
# - opening Blender
# - opening any Blender file
@persistent

def register():
bpy.utils.register_class(MyCollectionItem)
bpy.types.Scene.myCollection = bpy.props.CollectionProperty(type=MyCollectionItem)
# adding handlers defined above in the code
bpy.app.handlers.scene_update_post.append(onRegister)

def unregister():
bpy.utils.unregister_class(MyCollectionItem)
del bpy.types.Scene.myCollection

if __name__ == "__main__":
register()