Registering class method as handler gives wrong results

Hi,

has anyone ever tried to register a class method as a handler? I succeeded in registering it and it is actually called, however the data passed is wrong - very odd.

Example:


class foo:
  def scene_update(self, context):
     print("%i objects", len(bpy.data.objects))
  def __init__(self):
    bpy.app.handlers.scene_update_post.append(self.scene_update)

This will be called correctly, but the data.objects state will never change.

However, this does work:


def scene_update(context):
   print("%i objects", len(bpy.data.objects))

bpy.app.handlers.scene_update_post.append(scene_update)

Does anybody know what’s going on there?

No.

You might try


class foo:
    def notifiy(self):
        pass
    def __init__(self):
        def scene_update(context):
            self.notify()
            print("%i objects", len(bpy.data.objects))
        bpy.app.handlers.scene_update_post.append(scene_update)

I can’t see a reason why you would add a scene handler whenever you create a class instance. If you created 100, there would be 100 scene handlers calling the scene_update function for no reason - it will give you the same object count 100x and add a lot of overhead.

@pink vertex: What is your code supposed to do? Your handler registration won’t work… :wink:
@CoDEmanX: In this case, the instance can only exist once at a time.

In the meantime I found a global method more practical for other reasons. Using a class would have been cleaner, but, as said in the other topic, registering a class method handle is not possible.

It should be possible to define a function (almost) everywhere on the fly. The function has access to the local scope and keeps it.

Its called a closure and often is used in combination with @decorators.


l=[]

class foo:
    def __init__(self):
        self.value = 42
        banana = "banana"
        def func():
            self.value = 23
            print(banana)
        l.append(func)

f = foo()
print(f.value)
l[0]()
print(f.value)

Works in python.