Here is another way to refactor your code:
foo = data.get('foo')
bar = data.get('bar')
if foo:
if bar:
dofoobar()
else:
dofoo()
elif bar:
dobar()
I am not sure if this is cleaner or more readable than ChristianDean's answer.
Just for fun, you can also use dict
with boolean tuples as keys and functions as values:
{(True, True):dofoobar, (False, True):dobar, (True, False):dofoo}
You would use it like this:
data = {'foo': 'something'}
foo = data.get('foo')
bar = data.get('bar')
def dofoobar():
print('foobar!')
def dobar():
print('bar!')
def dofoo():
print('foo!')
actions = {(True, True):dofoobar, (False, True):dobar, (True, False):dofoo}
action = actions.get((foo is not None, bar is not None))
if action:
action()
source
share