I want to return a value depending on which among a set of functions returns true.
if a():
return 'a'
elif b():
return 'b'
else:
return 'c'
is there a more pythonic way of doing so?
If you can put all of the functions into an iterable:
functions = [a, b]
for func in functions:
if func():
return func.__name__
return "c"
This makes more sense when supplied with lots of functions, as the only thing that changes is functions (and optionally a 'default' return value). If you want this as a function:
def return_truthy_function_name(*functions, default):
"""Iterate over `*functions` until a function returns a truthy value, then return its name.
If none of the functions return a truthy value, return `default`.
"""
for function in functions:
if function():
return function.__name__
return default
I don't know if it's more pythonic, but it's shorter using 2 nested ternary expressions:
return 'a' if a() else ('b' if b() else 'c')
if there are more than 2 conditions, nesting ternary expressions becomes ludicrious and the loop approach of Coal_ answer (maybe using a list of tuples to associate the function call and the return value if there's no obvious relation between the 2) is better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With