2
$\begingroup$

I want a Boolean expression to check if an object exist in a specific collection. For instance, test whether "Sphere" exists in the collection "TEST_COL".

So I can run the expression and it returns True or False.

Screenshot of the Outliner showing an object in a collection.

$\endgroup$

3 Answers 3

3
$\begingroup$

Since you know the name of the object and the name of the collection, there are (at least) two ways to create such an expression. Both start with obtaining the actual things from their names. One is more reliable than the other so I will only give it.

object = bpy.data.objects["Cube"]
collection = bpy.data.collections["Collection"]
    
if collection in object.users_collection:
     print("yes")

In your case you would replace "Cube" with "Sphere" and "Collection" with "TEST_COL".

Note that this code will raise an exception if there is no object or collection with the specified names.

EDIT: Here's the same code in the form of a helper function:

def is_object_in_collection(object_name, collection_name):
    object = bpy.data.objects.get(object_name)
    if not object:
        return False
    collection = bpy.data.collections.get(collection_name)
    if not collection:
        return False
    return collection in object.users_collection
$\endgroup$
3
  • 1
    $\begingroup$ Actually I was intending for a dynamic collection name, like for when you don't know the collection name of the original object. But your code did give me the helper functions I needed to execute it myself. Thanks again :D $\endgroup$
    – NamanDeep
    Jan 7, 2022 at 16:55
  • 1
    $\begingroup$ OP asked for "So I can run the expression and it returns True or False." -> where does your answer return a true or false? $\endgroup$
    – Chris
    Jan 7, 2022 at 16:57
  • $\begingroup$ In the if statement Chris. Expressions return their values when they're evaluated. Anyway, while you were writing your comment, I added a function that returns a value, so it should be clearer. $\endgroup$ Jan 7, 2022 at 17:00
3
$\begingroup$

Collection.objects returns all objects of the collection: https://docs.blender.org/api/current/bpy.types.Collection.html#bpy.types.Collection.objects and bool() converts the value into a Bool.

One-liner:

>>> bool(bpy.data.collections['Collection'].objects.get('Cube'))
True
$\endgroup$
3
$\begingroup$

Object.users_collection returns all collections associated with the object: https://docs.blender.org/api/current/bpy.types.Object.html#bpy.types.Object.users_collection, in this case a generator expression is a good choice.

One-liner:

>>> 'Collection' in (i.name for i in bpy.data.objects['Cube'].users_collection)
True
$\endgroup$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .