Computing with Dabeaz

Subscribe
Archives
March 19, 2023

The if-return

The if-return

The other day, I came across someone questioning the following coding idiom:

def some_func(): 
    ... 
    if condition: 
        return True 
    else: 
        return False

Clearly such code must be written by a rank amateur. Why not this?

def some_func(): 
    ... 
    return condition

Well, there's certainly the issue of truthiness. Maybe condition is checking against a container of some kind.

def some_func(): 
    items = [ ]
    ...
    return items

If this case, returning itemsis decidedly quite different than returning True or False--especially speaking as someone who's had to spend a few hours chasing down some bug due to "truthiness."

Or maybe someone has written a boolean expression using and or or like this:

def some_func():
    ...
    return condition1 or condition2

It may not be obvious that and and or in Python don't actually return True or False. They return the value of condition1 or condition2 using short-circuit behavior.

>>> 3 and 4
3
>>> False or [1,2,3]
[1,2,3]
>>>

Again, this behavior is quite different than being explicit:

def some_func():
    ...
    if condition1 or condition2:
        return True
    else:
        return False

So, all things equal, I'd say the original code of returning True or False might not be the work of an amateur, but of someone who actually knows what they're doing.

Of course, you could also write something like this:

def some_func():
    ...
    return bool(condition)

But, that would just be silly. Although maybe not as silly as the professional solution of using a decorator:

from functools import wraps
def returns_bool(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return bool(func(*args, **kwargs))

@returns_bool
def some_func():
    return condition

All things equal, I'm perfectly happy with the explicitly unclever, but quite readable if-else idiom.

Cheers, Dave

Don't miss what's next. Subscribe to Computing with Dabeaz:
GitHub X YouTube