I have a couple of functions that return either a number or None
. I want my wrapper function to return the first result that is not None
. Is there any other way to do this than as following?
def func1():
return None
def func2():
return 3
def func3():
return None
def wrapper():
result = func1()
if result is not None:
return result
result = func2()
if result is not None:
return result
result = func3()
if result is not None:
return result
I am aware of return func1() or alternative
; which returns the outcome of func1()
unless it is None
, then alternative
is returned. In the most optimal situation I do something like (pseudo code):
return func1() or continue
return func2() or continue
return func3() or continue
You need a loop which will return the first non-None
value it finds.
def wrapper():
for f in [func1, func2, func3]:
result = f()
if result is not None:
return result
If every function returns None
, wrapper
will as well by reaching the end of the body without an explicit return
.
Shortened slightly in Python 3.8 or later,
def wrapper():
for f in [func1, func2, func3]:
if (result := f()) is not None:
return result
You can also make use of the any
function:
def wrapper():
if any((result := f()) is not None for f in [func1, func2, func3]):
return result
(I prefer the explicit loop; YMMV.)