[SOLVED] Strange behavior with index and mode_set

So maybe someone can tell me if I’m doing something wrong here, or this is a bug.

Running the code below on a selected cube goes and cycles through each face and prints the index of each face. But the strange thing that I can’t figure out, is when using “bpy.ops.object.mode_set()”, the index numbers go totally crazy.

import bpy

obj = bpy.context.object
polys = obj.data.polygons

# Using mode_set
for i in polys:
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.object.mode_set(mode='OBJECT')
    print("i.index when using mode_set", i.index)

# Not using mode_set
for i in polys:
    print("i.index NOT using mode_set", i.index)

This is what this results in using 2.62 r45222:
i.index when using mode_set -24
i.index when using mode_set 229
i.index when using mode_set 254
i.index when using mode_set 195
i.index when using mode_set 208
i.index when using mode_set 149

i.index NOT using mode_set 0
i.index NOT using mode_set 1
i.index NOT using mode_set 2
i.index NOT using mode_set 3
i.index NOT using mode_set 4
i.index NOT using mode_set 5

Using 2.61 (using data.faces instead of data.polygons) I get this result:
i.index when using mode_set -7893618
i.index when using mode_set 1
i.index when using mode_set -7893616
i.index when using mode_set 3
i.index when using mode_set -7893614
i.index when using mode_set 5

i.index NOT using mode_set 0
i.index NOT using mode_set 1
i.index NOT using mode_set 2
i.index NOT using mode_set 3
i.index NOT using mode_set 4
i.index NOT using mode_set 5

Some strange results! Is there something wrong with the way I’m trying to get the index when switching in and out of Edit mode? Or is this just funky behavior?

I may be doing something completely backwards, I’m just curious if anyone has any insight on this as I am baffled.

Looks like a bug
Better report it as such

I’d say your pointer to individual polys gets borked because blender rebuilds the mesh after you go out of edit mode (or the other way around) so it’s just pointing to some random freed/reused memory.

One of the limitations of blender (and python a bit) so, basically, don’t reference data that’s stale like that.

Uncle Entity is correct. If you read the Gotchas it clearly states that you need to re-fetch a datablock after you toggle edit mode. Read Edit Mode / Memory Access.

Ah, thanks for the heads up! Everything totally makes sense now.

It was easy to get by the issue so it wasn’t a big deal, I was more curious than anything. Should have read the gotchas a little more thoroughly, right at the very bottom just like Atom says it clearly states:

http://www.blender.org/documentation/blender_python_api_2_62_0/info_gotcha.html?highlight=gotchas#edit-mode-memory-access