Hi everybody, I'm struggling with context, operators and selection. I would like to write a script that selects a single object, let's say a Cube, even though the current mode may be EDIT on some other object, let's say Cube.001. If you could provide the code to do so it would be great. I did two experiments, one that does not work in all cases, and one that looks like it is behaving correctly but I'm scared it may be doing something unstable too.

The first experiment fails exactly in the case in which Cube.001 is selected, it is in EDIT mode, and the script attempts to select Cube. What happens is that Blender switches to OBJECT mode on Cube, selecting it, but if you look at the ouliner for Cube.001, you will see that its mesh datablock of Cube.001, between the name and the visibility eye, remains selected. In the 3D View, you also see that Cube.001 still looks like it is in EDIT mode. If you execute my script, you will also notice that the duplicate operator fails because the context is incorrect.

The second experiment behaves correctly in this test case; the only difference is that I set EDIT mode on Cube before setting OBJECT.