Changing vertex colors through python I'm trying to get and set the vertex colors of a mesh through a python script. However, the script seems unable to find the vertex color data, claiming the data set has length 0 despite that clearly not being the case.

import logging
logging.basicConfig(level=logging.DEBUG,format='(%(threadName)-10s) %(message)s',)

obj = bpy.context.edit_object

mesh = obj.data

if not mesh.vertex_colors:
    mesh.vertex_colors.new()
    logging.debug("Mesh had no vertex colors, adding them")

color_layer = mesh.vertex_colors.active

logging.debug(mesh)
logging.debug(mesh.vertex_colors)
logging.debug(len(color_layer.data))

if len(color_layer.data) &gt; 0:
    i = 0
    for poly in mesh.polygons:
        for idx in poly.loop_indices:
            color_layer.data[i].color = (1.0, 0.0, 0.0)
            i += 1




This is the console output:  


  (MainThread) bpy_struct, Mesh("Cube")
  (MainThread) bpy_collection1, LoopColors
  (MainThread) 0




Here is my mesh, which very clearly has a non-zero list of vertex colors:



Anyone knows what's happening?
It seems that the way to go about it is, unintuitively, to exit edit mode into object mode in order to perform any vertex-level stuff, and then re-enter edit mode at the end of your script.



mode = bpy.context.active_object.mode
bpy.ops.object.mode_set(mode = 'OBJECT')

ob = bpy.context.active_object

for vcol in ob.data.vertex_colors:
#sample or do stuff to the vertex colors

bpy.ops.object.mode_set(mode=mode)