Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of returning a value depending of results of multiple functions

Tags:

python

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?

like image 415
Nijan Avatar asked Nov 18 '25 16:11

Nijan


2 Answers

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
like image 110
Daniel Avatar answered Nov 21 '25 04:11

Daniel


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.

like image 45
Jean-François Fabre Avatar answered Nov 21 '25 06:11

Jean-François Fabre