# Operator bpy.ops.rigidbody.object_add.poll() failed, context is incorrect

Here's a simple code that works fine as far as the .blend file with the object I'm modifying is already open.

obj = bpy.data.objects['obj']
obj = C.scene.objects.active
obj.select = True
obj.rigid_body.type = 'PASSIVE'


However, if I add a line at the beginning of my code to open the file using python,

bpy.ops.wm.open_mainfile(filepath=task_path+ str(x) +".blend")


I get the following error: RuntimeError: Operator bpy.ops.rigidbody.object_add.poll() failed, context is incorrect

I'm sorry to ask the same (or similar) question twice, but believe me, I've been working on this problem for weeks, read everything online about the "context is incorrect" error and unsuccessfully tried multiple things to solve it. Nothing works and the problem seems to be related to opening the file using python (bpy.ops.wm.open_mainfile). Any clue about what's happening? Thanks a lot for your help!!

• – batFINGER Jul 15 at 15:43
• Thanks @batFINGER I understand the problem now, I think. I'm trying to use a persistent handler but I'm not quite sure how. Any help appreciated. Thanks – ANB Jul 15 at 18:54

Just in case this is useful for somebody in the future, here's what seems to work for me:

import bpy
from bpy.app.handlers import persistent

@persistent