The bpy.ops
don't return a value and there isn't a function that will tell you if the object is smooth shaded or not; so you have to do it this way:
Smooth shading is a property of the individual polygons of a mesh. Here are two functions that let you set the shading mode or toggle it. They work by setting the use_smooth
field of each polygon in the mesh. In the first function, the value is set to the OnOff
argument's value. In the second, it is toggled.
There's some boiler plate error handling in each function to reduce the failure cases, if you try to run the function on an object that isn't a mesh, or properly initialized.
import bpy
def set_shading(object, OnOff=True):
""" Set the shading mode of an object
True means turn smooth shading on.
False means turn smooth shading off.
"""
if not object:
return
if not object.type == 'MESH':
return
if not object.data:
return
polygons = object.data.polygons
polygons.foreach_set('use_smooth', [OnOff] * len(polygons))
object.data.update()
def toggle_shading(object):
""" Toggle the shading mode of an object """
if not object:
return
if not object.type == 'MESH':
return
if not object.data:
return
polygons = object.data.polygons
for polygon in polygons:
polygon.use_smooth = not polygon.use_smooth
object.data.update()
If, for instance, you wanted to toggle the shading on the active object you would make a call like:
toggle_shading(C.active_object)