Say thing
can be one of foo
, bar
, baz
, or quux
. Additionally, self
has methods foo
, bar
, baz
and quux
. This is ok:
if thing == 'foo':
self.foo()
and this is fine:
if thing != 'quux':
getattr(self, thing)()
The things in the middle are murky. I myself would not consistently choose one way over the other. I might sometimes write
if thing == 'foo':
self.foo()
elif thing == 'bar':
self.bar()
and others write
if thing in ['foo', 'bar']:
getattr(self, thing)()
depending on how I expect the code to grow, more than anything else. To reach three branches, in my own code, would be rare, but I probably wouldn't flag it for review. I would flag four.
If things were more complicated (20 different values of thing
, 10 of them needing an action, say), I might
- create a class,
class throwaway(C):
notwanted1 = notwanted2 = notwanted3 = lambda _: None
(assuming type(self)==C
)
- use a dict,
d = {'foo': C.foo, 'bar': C.bar, 'baz': C.baz, ...}
d.get(thing, lambda _: None)(self)
again, depending.
Lastly,
class C:
def foo(self):
pass
foo.do_thing = True
def bar(self):
pass
bar.do_thing = False
# etc
so then,
method = getattr(self, thing)
if method.do_thing:
method()