Immediate mode Python API

This is an idea I am having for creating a nice wrapper around the Blender API, that will allow use the BPY in a more simple and friendly aspect.


import bpy

# ###################################################
# this is an immediate mode API for mutating class objects
# this can go to some other library file and be reused everywhere
class bleop:
    operator = None
    def begin(op):
        bleop.operator = op
    def end():
        bleop.operator = None
    def descr(desc):
        bleop.operator.bl_description = desc
    def label(label):
        bleop.operator.bl_label = label
    def idname(name):
        bleop.operator.bl_idname = name
    def execute(def_execute_self_context):
        bleop.operator.execute = def_execute_self_context
    def register():
        # make register function more clever
        # and prevent multiple registrations
        bleop.unregister()
        bpy.utils.register_class(bleop.operator)
    def unregister():
        try:
            bpy.utils.unregister_class(bleop.operator)
        except:
            pass
# ###################################################

# this is the hard defined operator
# (no meta programming used at all
# since class declarations can be
# defined explicitly and later be
# modified)
class Operator(bpy.types.Operator):
    pass

# load the class type once
bleop.begin(Operator) 

# and begin changing it's properties
bleop.descr("Description for simple operator")
bleop.label("Simple Operator")
bleop.idname("object.simple_operator")

# and now attach an execution method to it
def execute_method(self, context):
    for o in context.scene.objects:
        print("hello", o.name)
    return {'FINISHED'}

bleop.execute(execute_method)

# and finally register the operator
bleop.register()

# explicitly stop referencing the class
bleop.end()

Perhaps now in this simple operator is pointless, if you scale towards 20 operators and 20 panels and such you will realize that you need a much “higher level” approach so you won’t deal with low level concepts all the time. Also in another case you would be able to construct an entire list of items and then register everything in one loop.

Also one important thing is that you might consider that in this way you will loose ENCAPSULATION (having no ability to write extra methods inside the operator class). This is true. I have in mind in terms of architecture to avoid encapsulation at all costs. Instead rely on a much stronger MVC model, in that way BPY operators or panels must only be considered a way to connect the addon code to Blender.

What you can do to help, is to use the technique and create more test cases so you know how it should be better improved and how.

1 Like