Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a class dictionary to map to instance methods in Python

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?

like image 623
sourcenouveau Avatar asked Oct 16 '12 19:10

sourcenouveau


1 Answers

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).

like image 197
Martijn Pieters Avatar answered Sep 27 '22 18:09

Martijn Pieters