What is the most pythonic way to conditionally return a function

conditional-statements, function, python, return

Solution

Giving a name to the result of calling func1 is relatively cheap, so I'd do that, but write the function like this:

def func2(n):
    ret = func1(n)
    return ret if ret is not None else something_else

Problem

Say I have 2 functions. I want func2 to return func1 UNLESS func1 returns None, in which case func2 returns something else. There are two ways that I could do this, but they both feel slightly wrong. I could say: ``` def func1(n): if (condition): return foo def func2(n): if func1(n) is not None: return func1(n) else: return something_else ``` But this feels wrong because I have to call func1(n) twice (and func1(n) is a larger computation). To get around that, I could say: ``` def func1(n): if (condition): return foo def func2(n): foo = func1(n) if foo is not None: return foo else: return something_else ``` but this feels wrong because I don't think I should have to assign a new variable that will never get used again, just to check if func1 returned None. Is there an easier way to do this where I don't have to call func1 twice and I don't have to create a new variable? If this is the only way, which of the two would you recommend? I currently have it using the second way (Where I set foo to what func1 returned, than return foo unless foo == None) Also, keep in mind that in my real code, I call several different functions, and I want to return the first one that is not None, this is just a simpler version of code that gets the question across.

Original source

Related problems