# Python collection_duplicate() help

Is it possible to duplicate a collection from a Python script? When I do it manually, the Console shows bpy.ops.outliner.collection_duplicate(), however if I call it from script, there is a problem with context:

RuntimeError: Operator bpy.ops.outliner.collection_duplicate.poll() failed, context is incorrect

Does that mean that collection_duplicate() can be called only from the Outliner editor? If so, how to 'fake' it from a script?

This will duplicate the active collection in the outliner:

import bpy

for window in bpy.context.window_manager.windows:
screen = window.screen

for area in screen.areas:
if area.type == 'OUTLINER':
override = {'window': window, 'screen': screen, 'area': area}
bpy.ops.outliner.collection_duplicate(override)
break


From the documentation example here: Execution Context

• Works great! Thank you! – user1566515 Nov 12 '19 at 13:37

API method

If you know the collection you wish to dupe, and the collection you wish to parent to, consider something like below. Because a collection can have many parents, I'm not totally sure without using the outliner how to determine which instance of the collection is being duped, and hence where in the hierarchy to paste.

As a test, I've copied the context collection to to the scene collection, with and without linked data. Using a method that recursively creates a new collection and populates it with object copies from the source.

import bpy
for o in from_col.objects:
dupe = o.copy()
dupe.data = dupe.data.copy()

cc = bpy.data.collections.new(collection.name)

for c in collection.children:

# test script
context = bpy.context
scene = context.scene
col = context.collection
print(col, scene.collection)
assert(col is not scene.collection)
parent_col = context.scene.collection

copy(scene.collection, col)


Note

For a totally linked copy, ie the objects and collections within are linked copies then

cc = collection.copy()


will do the trick.

Related

Change active collection

• Thank you for a detailed answer. I tested it and it works as described. I marked another answer as correct because it appeared earlier and is a valid answer to this particular question. I also like your answer because it is a good working example of how to manipulate objects and collections. – user1566515 Nov 12 '19 at 13:36
• Cheers and No probs. On a purely semantics lilt: Despite the big green tick, it's "accepted" (by you) rather than being "correct" which implies other answers are unaccepted rather than incorrect lol. If I had my way would change SE such that any or all answers could be accepted. and one is "favoured" To quote RickyBlender "Happy Blending" – batFINGER Nov 12 '19 at 14:03
• Thank you for the explanation. I think "accepted" makes more sense :) – user1566515 Nov 12 '19 at 14:17