How does one get the most recently created collection?

After creating a collection with object.link_to_collection, how do you get the collection that was created? it’s an operator, so the return type is just a status string. the collection type doesn’t have an index. the list of collections in is just an unordered prop_collection. bpy.context.collection doesn’t change until the user actively selects the collection in the outliner. I could try to find it by name but there’s no guarantee the name is what I called it in the operator because it could have been auto-renamed due to a collision.

I’m at a loss as to what we’re supposed to do with this on the addon side of things. The only thing I can think of is to either somehow scrape the string from INFO output and parse the name out of it, or make a list of all the collections before I make mine and then diff it to find the one that I made. As an example- this works, but uhhh… feels super wrong.

before = [ for c in]
bpy.ops.object.link_to_collection(collection_index=0, is_new=True, new_collection_name=collection_name)
diff = list(set([ for c in]) - set(before))        
new_collection_name = diff[0]

As a tangentially related side note- any reason why the Scene Collection is called “Master Collection” in Seems like the name got changed on the user-facing side of things and never updated… should this be logged as a bug?

Another annoying collections operator gripe- bpy.ops.collection.objects_remove seems prone to throwing type exceptions, because the selected objects could be part of any number of different collections and there’s no guarantee that they’re even members of the collection you’re trying to remove them from. Why not just silently skip that object rather than raise an exception and make the entire script fail?

Don’t use operators for scripting if you can avoid it, they are not designed to be a scripting API. Instead use functions like and

1 Like

That’s perfect, does exactly what I’m looking for! Thanks

Perhaps, in the ‘Documentation’ section, we could add a tutorial on the new collection API?
I was having trouble finding the API for collections last week when I was doing something similar, ended up using ops even though I knew it was ‘wrong.’ Probably these kinds of questions will be answered by the updated documentation in the next few weeks.

Thanks :slight_smile: !