Chuck Chuck - 3 months ago 4
Python Question

Is there a better way to structure these function calls?

I have a class that needs one of a number of helper classes. It will only ever use one of these helpers, and all of them have the same interface. So I'm writing code like this:

if self.type == Class.Type.a:
helper = A()
elif self.type == Class.Type.b:
helper = B()
elif self.type == Class.Type.c:
helper = C()


Currently there are about 5 different types, but I can see that expanding, and this structure is already in my class about four or five times, and I can see the need for this logic at least a dozen times.

Is there a better way to perform this logic? I think that Python often uses dictionaries to perform this type of logic, but I don't yet see how that idiom can work.


You can indeed use a dictionary:

my_dict = {Class.Type.a:A,

helper = my_dict[self.type]()