I want to know how to make a function return the return value of a nested function, if the return value of the nested function is not None.
To make my code work, I could just copy the code of the nested function in my main function, but this is too repetitive (DRY). I looked into some questions with copying functions with from functool import partial but this just allows you to have another function with different variables or docstring. Furthermore I've glanced at all related questions and none seem to have an elegant piece of code (to do this simply).
Here the main function ExtractOne is fed a list of numbers. Generally (relevant to my code) the 4th element is one, so that element is checked with CheckIfOne function. If this is the case, the function returns 1 and is thus exited. If that is not the case, then the code continues by checking all the elements in the fed list if they're a one, again, using CheckIfOne for each element. If the element is one, ExtractOne should return 1, thus breaking the for loop and function.
Here's a snippet of what works. It's copying the return value of CheckIfOne (the nested function) onto a variable a, checking if a is not None, and returning a if this is the case.
Example 1:
def CheckIfOne(part):
if part == 1:
return 1
def ExtractOne(parts):
#4th element is generally 1
a = CheckIfOne(parts[3])
if a:
return a
#else scan through the list for 1
for part in parts:
a = CheckIfOne(part)
if a:
return a
>>> ps = [1,2,3,4,5]
>>> ExtractOne(ps)
1
>>>
Here's how I would like it to look like, but of course this is not how nested functions work, the nested function returns a value and this must be copied onto a variable and that variable checked if it's not None and then returned, like in the above snippet.
Example 2:
def CheckIfOne(part):
if part == 1:
return 1
def ExtractOne(parts):
#4th element is generally 1
CheckIfOne(parts[3])
#else scan through the list for 1
for part in parts:
CheckIfOne(part)
>>> ps = [1,2,3,4,5]
>>> ExtractOne(ps)
>>>
However, it does work when I just copy the code of CheckIfOne, but this violates the DRY rule.
Example 3:
def ExtractOne(parts):
#4th element is generally 1
if parts[3] == 1:
return 1
#else scan through the list for 1
for part in parts:
if part == 1:
return 1
>>> ps = [1,2,3,4,5]
>>> ExtractOne(ps)
1
>>>
I expect there to be a simple, pythonic python syntax to just copy the code of the nested function onto the main piece of code like in example 3.