I’ve got some code that looks like the following:
if command == 'a':
do_a(a, b, c)
elif command == 'b':
do_b(a, b, c)
elif command == 'c':
do_c(a, b, c)
How can I replace this type of thing with something more elegant? Perhaps, something along the lines of do_[command](a, b, c) where the function that is called is dependent upon the command?
Is it even possible?
You could do something like that using "reflection", calling the function by string name, like explained here:
Python: call a function from string name
BUT
That wouldn’t be more elegant, it would be less readable, and easier to screw up if you don’t have absolute control over what’s passed as
command.Your version is just fine:
If you really want to avoid the
elif‘s I would go with thedictof functions approach that was suggested in the comments.Keep away from eval for things like this.