8

I can access objects belonging to a collection like so:

objects_in_collection = bpy.data.collections["My_Collection"].objects

How can I access the collection a specific object belongs to?

brockmann
  • 12,613
  • 4
  • 50
  • 93
coCoKNIght
  • 884
  • 1
  • 6
  • 12

2 Answers2

16

Object.users_collection property returns a tuple containing all linked collections:

>>> obj = bpy.context.object
>>> obj.users_collection
(bpy.data.collections['Collection'],)
brockmann
  • 12,613
  • 4
  • 50
  • 93
  • 2
    Many thanks! I also needed to get the name of the collection and was able to do so like this: ob.users_collection[0].name – coCoKNIght Mar 21 '19 at 14:59
  • 1
    @brockmann :: Is the result always by order? e.g. [0] = direct parent? The official document in your link lacks detail. – cppBeginner Jul 18 '20 at 04:10
  • 2
    Not sure, just test it. If not the case, you can sort it: https://blender.stackexchange.com/questions/146685/how-to-obtain-the-parent-of-a-collection-using-python/172581#172581 @cppBeginner – brockmann Jul 18 '20 at 18:16
  • This doesn't seem to work in drivers. – Will Chen Apr 18 '21 at 22:26
0

Select this object by name and it should take you to the right collection. Selection by name is described in this section.

Lukasz-40sth
  • 3,062
  • 7
  • 19
  • 30