I have a long if-elif chain, like this:
class MyClass:
def my_func(self, item, value):
if item == "this":
self.do_this(value)
elif item == "that":
self.do_that(value)
# and so on
I find that difficult to read, so I prefer to use a dictionary:
class MyClass:
def my_func(self, item, value):
do_map = {
"this" : self.do_this,
"that" : self.do_that,
# and so on
}
if item in do_map:
do_map[item](value)
It’s silly to recreate the map every time the function is called. How can I refactor this class so that the dictionary is only created once, for all instances? Can I somehow turn do_map into a class member, yet still map to instance methods?
You have lots of options!
You could initialize the map in the
__init__method: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:
Or you can manually bind functions in a class-level dictionary to your instance using the
__get__descriptor protocol method:This is what
self.method_namedoes under the hood; look up themethod_nameattribute on the class hierarchy and bind it into a method object.Or, you could pass in
selfmanually: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).