Skip to content Skip to sidebar Skip to footer

What Is The Most Pythonic Way To Conditionally Return A Function

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 f

Solution 1:

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

deffunc2(n):
    ret = func1(n)
    return ret if ret isnotNoneelse something_else

Solution 2:

You definitely don't want to call func1 twice - as well as being inefficient, func1 may have side effects or produce a slightly different answer depending on the state at the time.

Also, there is no need for the else after a return as the return exited the function.

A revised version of your second option would be:

deffunc1(n):
    if condition:
        return foo

deffunc2(n):
    foo = func1(n)
    if foo isNone:
        return something_else
    return foo

Note that this works even if 'func1' returns a falsey value.

Alternatively, noting the content of func1, could you do:

deffunc1(n):
    return foo

deffunc2(n):
    foo = func1(n)
    if condition:
        return foo
    return something_else

It depends on what the real content of func1 actually is.

Solution 3:

As a completely different take from my previous answer, based on your comment to iCodez:

deffunc1(n):
    return ham

deffunc2(n):
    return jam

deffunc3(n):
    return spam

defmainfunc(n):
    for f in (func1, func2, func3):
        foo = f(n)
        if foo isnotNone:
            return foo

Post a Comment for "What Is The Most Pythonic Way To Conditionally Return A Function"