I'm trying to do a sort of type handling function registration, using this code:
types = {}
def type_handler(name):
def wrapper(f):
types[name] = f
return f
return wrapper
@type_handler('a')
def handle_a(a):
...
@type_handler('b'):
def handle_b(b):
...
def handle(x):
types[x.name](x)
This works fine, but now I want it to work inside a class.
I tried this:
class MyClass(object):
types = {}
def type_handler(name):
def wrapper(f):
types[name] = f ## global name 'types' is undefined
return f
return wrapper
@type_handler('a')
def handle_a(self, a):
...
@type_handler('b'):
def handle_b(self, b):
...
def handle(self, x):
self.types[x.name](self, x)
But it says global name 'types' is undefined
.
I tried changing it to
def type_handler(name):
def wrapper(f):
MyClass.types[name] = f ## global name 'MyClass' is undefined
return f
return wrapper
But now it says global name 'MyClass' is undefined
.
What can I do to make this work?
I know I can do something like:
def handle(self, x):
self.__getattribute__('handle_%s' % x.name)(self, x)
But I prefer function registration rather name based lookup.