Pythonic way to avoid "if x: return x" statements Pythonic way to avoid "if x: return x" statements python python

Pythonic way to avoid "if x: return x" statements


Alternatively to Martijn's fine answer, you could chain or. This will return the first truthy value, or None if there's no truthy value:

def check_all_conditions():    return check_size() or check_color() or check_tone() or check_flavor() or None

Demo:

>>> x = [] or 0 or {} or -1 or None>>> x-1>>> x = [] or 0 or {} or '' or None>>> x is NoneTrue


You could use a loop:

conditions = (check_size, check_color, check_tone, check_flavor)for condition in conditions:    result = condition()    if result:        return result

This has the added advantage that you can now make the number of conditions variable.

You could use map() + filter() (the Python 3 versions, use the future_builtins versions in Python 2) to get the first such matching value:

try:    # Python 2    from future_builtins import map, filterexcept ImportError:    # Python 3    passconditions = (check_size, check_color, check_tone, check_flavor)return next(filter(None, map(lambda f: f(), conditions)), None)

but if this is more readable is debatable.

Another option is to use a generator expression:

conditions = (check_size, check_color, check_tone, check_flavor)checks = (condition() for condition in conditions)return next((check for check in checks if check), None)


Don't change it

There are other ways of doing this as the various other answers show. None are as clear as your original code.