Abandon the approach of edit mode/non-edit mode and just focus on the datablock. Materials for faces are specified via material_index inside the datablock of a mesh type object.
Add a Suzanne mesh to the scene and try this code:
import bpy, random
ob = bpy.data.objects.get("Suzanne")
if ob != None:
# Create a materials.
mat_one = bpy.data.materials.get("mat_one")
if mat_one == None:
mat_one = bpy.data.materials.new("mat_one")
mat_one.diffuse_color = (random.random(),random.random(),random.random())
mat_two = bpy.data.materials.get("mat_two")
if mat_two == None:
mat_two = bpy.data.materials.new("mat_two")
mat_two.diffuse_color = (random.random(),random.random(),random.random())
# Add materials to slots.
ob.data.materials.append(mat_one)
ob.data.materials.append(mat_two)
# Determine random count and poly count.
rnd_face_count = 12
l = len(ob.data.polygons)
# Note: By default all faces have a material index of 0.
for i in range(rnd_face_count):
# Generate a random face index.
rnd_face_index = random.randint(0,(l-1))
ob.data.polygons[rnd_face_index].material_index = 1
This is not the cleanest code but it shows one way to accomplish the task mentioned. If you run this code twice, however, you will discover that you are building up a list of new materials on the Suzanne object.
.material_indexhas a default of 0, which is automatically the first material). – CodeManX Apr 13 '14 at 21:27