I want to be able to create a python decorator that automatically "registers" class methods in a global repository (with some properties).
Example code:
class my_class(object):
@register(prop1,prop2)
def my_method( arg1,arg2 ):
# method code here...
@register(prop3,prop4)
def my_other_method( arg1,arg2 ):
# method code here...
I want that when loading is done, somewhere there will be a dict containing:
{ "my_class.my_method" : ( prop1, prop2 )
"my_class.my_other_method" : ( prop3, prop4 ) }
Is this possible?
Not easy, but if you are using Python 3 this should work:
Note that you can not have method names equal to the decorator name in the meta-typed class, because they are automatically deleted by the
del
command in the metaclass's__new__
method.For Python 2.6 I think you would have to explicitly tell the decorator the class name to use.
Not with just a decorator, no. But a metaclass can automatically work with a class after its been created. If your
register
decorator just makes notes about what the metaclass should do, you can do the following:printing
Here's a little love for class decorators. I think the syntax is slightly simpler than that required for metaclasses.
Not as beautiful or elegant, but probably the simplest way if you only need this in one class only:
No. The decorator receives the function before it has become a method, so you don't know what class it is on.
If you need the classes name, use Matt's solution. However, if you're ok with just having the methods name -- or a reference to the method -- in the registry, this might be a simpler way of doing it:
print