What's the best way to see if a prim has a specific named collection?

I want to see if my prim has a collection with a specific name or not.
I tried on my own, but then asked nvidia’s ai code generator for help and it suggested this:

Write a python function that takes a prim and a collection name and determines if that collection already exists on the prim.

from pxr import Usd, UsdGeom, Sdf

def collection_exists_on_prim(prim, collection_name):
    """
    Check if a collection with the given name already exists on a prim.

    Args:
        prim (Usd.Prim): The prim to check.
        collection_name (str): The name of the collection to look for.

    Returns:
        bool: True if the collection exists on the prim, False otherwise.
    """
    if prim.HasAPI(Usd.CollectionAPI):
        collection_api = Usd.CollectionAPI.Get(prim, collection_name)
        return collection_api is not None
    return False

# Example usage:
stage = Usd.Stage.CreateInMemory()
prim = stage.DefinePrim("/MyPrim", "Xform")
collection_name = "MyCollection"
Usd.CollectionAPI.Apply(prim, collection_name)
print(collection_exists_on_prim(prim, collection_name))  # Output: True

Which okay… addresses half the issue. But then I can:

print(collection_exists_on_prim(prim, "i_dont_exist")) 

which also gives me True.

So then I could do something like:

collection_api_names = [x.GetName() for x in Usd.CollectionAPI.GetAllCollections(prim)]
# then test
collection_name in collection_api_names

and that will work. But I feel kind of icky.

The AI missed that there are overloads of HasAPI that take both a schema name and an instance name, so:

prim.HasAPI(Usd.CollectionAPI, "i_dont_exist")

should return False.

1 Like

Thanks spiff!

So followup question: I think these 2 lines of code do the same thing. Are there any differences?

coll_api = Usd.CollectionAPI.Apply(my_prim, "collection_name")

coll_api = Usd.CollectionAPI(my_prim, "collection_name")

There actually are big differences!

This actually applies the schema to the prim - it’s an authoring operation.

This one simply gives you a schema object that is useful only if the schema has already been applied - it does no authoring.

2 Likes