Error in Assigning an Object to Multiple Collections

Hi,

In the UI, you can assign an object to multiple collections.
However, when I do so using Python, it gives an error of

RuntimeError: Error: Object 'Object' already in collection 'Collection'

Here is the code I used

col = bpy.data.collections['Collection_Name']
obj = bpy.data.objects['Object_Name']

col.objects.link(obj)

Is there a way around this?
Thank you for looking at my problem.

Please ignore this thread.
There was erroneous line my code where an object is assigned to a collection it already belongs to.
So this is not the case of “error-in-assigning-an-object-to-multiple-collections”.

The code above works as expected with an added check if the obj is being linked to its current collectioni.

so and where is the answer?

@bentraje You can’t link an object to a collection if it’s already linked to the collection. Two solutions are :

Ask for permission

if obj.name not in col.objects:
    col.objects.link(obj)

Ask for forgiveness

try:
    col.objects.link(obj)
except RuntimeError:
    pass