I am looking for handling differing number of returned values from invoked functions in a set number of target variables. The following simplified snippet is a starting illustration:
def f1(): return 1,2,3
def f2(): return 4,5
a,b,c = f1()
a,b,c = f2() # How to massage this call: default of some sort?
So the objective would be to unpack either 2 or 3 results into three output variables.
Consider that the f()
being invoked may be one of (many functions..) that mostly all return only two variables .. but there is a need to add a third parameter to maybe one or two of them.
The motivation here: an existing codebase that presently returns only two variables. But I need to add a third one. It would be helpful to leave the existing code mostly alone and simply handle the missing third parameter gracefully.
What construction could be used here?
答案 0 :(得分:1)
You are unpacking the result of those two functions, instead of doing that perhaps you could assign the result to a single variable then test that for length. much like here: ValueError: need more than 2 values to unpack in Python 2.6.6
t = list(f2())
if len(t) > 2:
# Can use the third result!
c = t[2]
答案 1 :(得分:1)
Generally, you could save all of the returned values to a single variable and then access them using indexing.
x1 = f1() # x1[0] = 1, x1[2] = 2, etc.
x2 = f2()
If you need to use a,b,c
for separate pieces of code, you can pack the variables using:
a,b,*c = f1()
a,b,*c = f2()
This will capture all values beyond the first 2 returned by f1
or f2
as a list in c
.
If you are in version 2.7, you can take a few extra steps to ensure assigning c
doesn't give an error. You capture the output of your function as a list, then extend the list to the length of your variables using None
. After that, you can assign directly to a,b,c
# assumes you have 3 variables: a,b,c
res = list(f2())
res += [None]*(3-len(res))
a,b,c = res