Custom operator to toggle lamp energy not working I wrote this simple python script for Blender 2.69, which creates a new operator. The operator is supposed to change the energy for four lamps in the scene (essentially switching them off and on again). However, while the script runs fine and creates the operator itself, when I select the operator, it has no effect on the lamps' energy.

Entire script:

import bpy


def main(context):
    for ob in context.scene.objects:
        print(ob)


class LightsOperator(bpy.types.Operator):

    bl_idname = "object.lights_operator"
    bl_label = "Headlight Operator"

@classmethod
def poll(cls, context):
    return context.active_object is not None

def execute(self, context):

    if bpy.data.objects['headlight1'].energy==0.0:
        bpy.data.objects['headlight1'].energy = 0.8
    else:
        bpy.data.objects['headlight1'].energy = 0.0


    if bpy.data.objects['headlight2'].energy==0.0:
        bpy.data.objects['headlight2'].energy = 0.8
    else:
        bpy.data.objects['headlight2'].energy = 0.0

    if bpy.data.objects['headlight3'].energy==0.0:
        bpy.data.objects['headlight3'].energy = 0.8
    else:
        bpy.data.objects['headlight3'].energy = 0.0

    if bpy.data.objects['headlight4'].energy==0.0:
        bpy.data.objects['headlight4'].energy = 0.8
    else:
        bpy.data.objects['headlight4'].energy = 0.0

def register():
    bpy.utils.register_class(LightsOperator)


def unregister():
    bpy.utils.unregister_class(LightsOperator)


if __name__ == "__main__":
    register()

    # test call
    bpy.ops.object.lights_operator()
Here is a variation of the script that works on all lamp objects with their name (ob.data.name! ) starting with "headlight" (case insensitive):

import bpy

class LightsOperator(bpy.types.Operator):
    bl_idname = "object.lights_operator"
    bl_label = "Headlight Operator"

    def execute(self, context):

        for ob in context.scene.objects:
            if not ob.type == 'LAMP':
                continue
            lamp = ob.data
            if lamp.name.lower().startswith("headlight"):
                lamp.energy = 0.0 if lamp.energy &gt;= 0.8 else 0.8

        return {'FINISHED'}

def register():
    bpy.utils.register_class(LightsOperator)

def unregister():
    bpy.utils.unregister_class(LightsOperator)

if __name__ == "__main__":
    register()

    # test call
    bpy.ops.object.lights_operator()


Note that it toggles the lights between 0.0 and 0.8, no matter what the initial value is. If you want to toggle only those with a specific energy, keep rounding errors in mind - it isn't really 0.8 unless you round(lamp.energy, 1):

&gt;&gt;&gt; lamp.energy = 0.8

&gt;&gt;&gt; lamp.energy == 0.8
False

&gt;&gt;&gt; lamp.energy
0.800000011920929

&gt;&gt;&gt; round(lamp.energy, 1)
0.8