Page MenuHome

bpy.props operator example misses property access
Closed, ResolvedPublic

Description

The Operator Example for using properties in an operator shows this code:

class DialogOperator(bpy.types.Operator):
    bl_idname = "object.dialog_operator"
    bl_label = "Property Example"

    my_float = bpy.props.FloatProperty(name="Some Floating Point")
    my_bool = bpy.props.BoolProperty(name="Toggle Option")
    my_string = bpy.props.StringProperty(name="String Value")

    def execute(self, context):
        print("Dialog Runs")
        return {'FINISHED'}

    def invoke(self, context, event):
        wm = context.window_manager
        return wm.invoke_props_dialog(self)

This code has two downsides.

  1. It promotes a blocking UI design, where the user is shown a popup before actually executing the operator.
  2. It doesn't show how to actually use the property values.

I would suggest something like:

class OBJECT_OT_property_example(bpy.types.Operator):
    bl_idname = "object.property_example"
    bl_label = "Property Example"

    my_float = bpy.props.FloatProperty(name="Some Floating Point")
    my_bool = bpy.props.BoolProperty(name="Toggle Option")
    my_string = bpy.props.StringProperty(name="String Value")

    def execute(self, context):
        self.report({'INFO'}, 'F: %.2f  B: %s  S: %s' % (self.my_float, self.my_bool, self.my_string)
        print('My float:', self.my_float)
        print('My bool:', self.my_bool)
        print('My string:', self.my_string)
        return {'FINISHED'}

This actually shows how to use the properties in the code, and doesn't block the UI. A nice touch would be to add an explanation that the properties are also shown in the redo panel in the 3D view.

Note that I also changed the bl_idname, as this is an example about properties, not about dialogue boxes, and changed the class name to use the standard operator naming convention.

Event Timeline

I agree since the example with invoking a pop-up is already mentioned here on the Operator page.
The bpy.props page can include a link to it, where the three possibilities related to operator drawing / accessing properties can be explained in more depth, possibly including a notice about some drawbacks of each approach.

Sybren A. Stüvel (sybren) lowered the priority of this task from 90 to Normal.