Skip to content

Return identity

Sourcery refactoring id: return-identity

Description:

Return booleans directly rather than wrapping them in a conditional that returns True or False

Before:

def function(a, b):
    if isinstance(a, b) or issubclass(b, a):
        return True
    return False

After:

def function(a, b):
    return isinstance(a, b) or issubclass(b, a)

Explanation:

Where we reach the end of a method and want to return True or False, a common way of doing so to explicity return them.

However, it's neater just to return the result directly.

This can only be done if the expression evaluates to a boolean. In this example:

def any_hats(self, wardrobe):
    hats = [item for item in wardrobe if is_hat(item)]
    if hats or self.wearing_hat():
        return True
    return False
We can't do this exact refactoring, since now we could be returning the list of hats rather than True or False. To make sure we're returning a boolean, we can wrap the return in a call to bool():
def any_hats(self, wardrobe):
    hats = [item for item in wardrobe if is_hat(item)]
    return bool(hats or self.wearing_hat())

Back to top