Using a class dictionary to map to instance methods in Python
My (untested) take, with a little caching:
class Something(object):
def __init__(self):
self.__do_map = {}
def my_func(self, item, value):
self.__do_map.setdefault(item, getattr(self, 'do_{}'.format(item)))(value)
OTOH, you could get the unbound methods, then explicitly pass self as the first instance...
class Something(object):
_do_methods = {}
def __init__(self:
pass
def my_func(self, item, value):
ubf = Something._do_methods.setdefault(item, getattr(Something, 'do_{}'.format(item)))
ubf(self, value)
def do_test(self, value):
print 'test is', value
You have lots of options!
You could initialize the map in the __init__
method:
def __init__(self):
self.do_map = {"this": self.do_this, "that": self.do_that}
Now the methods are bound to self
, by virtue of having been looked up on the instance.
Or, you could use a string-and-getattr approach, this also ensures the methods are bound:
class Foo(object):
do_map = {"this": "do_this", "that": "do_that"}
def my_func(self, item, value):
if item in self.do_map:
getattr(self, self.do_map[item])(value)
Or you can manually bind functions in a class-level dictionary to your instance using the __get__
descriptor protocol method:
class Foo(object):
def do_this(self, value):
...
def do_that(self, value):
...
# at class creation time, the above functions are 'local' names
# so can be assigned to a dictionary, but remain unbound
do_map = {"this": do_this, "that": do_that}
def my_func(self, item, value):
if item in self.do_map:
# __get__ binds a function into a method
method = self.do_map[item].__get__(self, type(self))
method(value)
This is what self.method_name
does under the hood; look up the method_name
attribute on the class hierarchy and bind it into a method object.
Or, you could pass in self
manually:
class Foo(object):
def do_this(self, value):
...
def do_that(self, value):
...
# at class creation time, the above functions are 'local' names
# so can be assigned to a dictionary, but remain unbound
do_map = {"this": do_this, "that": do_that}
def my_func(self, item, value):
if item in self.do_map:
# unbound functions still accept self manually
self.do_map[item](self, value)
What you pick depends on how comfortable you feel with each option (developer time counts!), how often you need to do the lookup (once or twice per instance or are these dispatches done a lot per instance? Then perhaps put binding the methods in the __init__
method to cache the mapping up front), and on how dynamic this needs to be (do you subclass this a lot? Then don't hide the mapping in a method, that's not going to help).