Set active collection

It may be too early to ask this question because collections are still under construction, but it’s literally the only thing that I can’t get to work in 2.8’s Python api.

After I add a new collection, I would like to set it as the active collection - basically the same functionality as selecting it in the outliner. I’ve tried many things and just can’t get this to work. Is this still under construction or am I missing something?

Other than that I am loving the new collections system to organize scenes, and The Grove is going to make good use of it. In fact, the entire code is already ported to Blender 2.8 and everything is working great!

It’s set per view layer as bpy.context.view_layer.collections.active. However the tricky thing is that this is a per view layer LayerCollection, rather than a Collection datablock.

You can traverse the tree of LayerCollection in view_layer.collections and find the one that matches a specific Collection, and then set that. But we really need a simpler API for this.

Thank you for the quick answer, Brecht! That made it work. This quick line below indeed does the trick to select the collection that was last added, give it was added to the master collection:
context.view_layer.collections.active = context.view_layer.collections[0].children[-1]

I think why I couldn’t figure it out, and why it still boggles my mind, is that context.view_layer.collections.active is not of type Collection, but of type LayerCollection. Perhaps it should be named context.view_layer.layer_collections ?

This is a quick update for people that happen to stumble upon this thread. There has just been a change in the API. There was an example in my last post, to select the collection that was last added. This example no longer works. Here’s a new way to do this:

context.view_layer.active_layer_collection = context.view_layer.layer_collection.children[-1]