Reputation: 287
Suppose we have
def f_1():
return (3, 4)
def f_2():
return 2
The functions are given. It is not code that I can modify. We know they return either an integer or a sequence of them.
I would like to assign the return to a variable, where the variable should take only the first of the integers if the return is a sequence of them.
Is there a build-in syntactic device in Python that allows me to do this?
for function in [f_1, f_2]:
...
x = function()[0] # Works for f_1, breaks for f_2
y = function() # Works for f_2, assigns (3, 4) for f_1 while
# we really would like only the 3 to be the
# assigned value
Note: Assume that we don't know which of the functions return the sequence and which return just a number.
Upvotes: 1
Views: 78
Reputation:
Is there a build-in syntactic device
No. The usual practice is to ask for forgivness:
x = function()
try:
x = x[0]
except TypeError:
pass
Upvotes: 2
Reputation: 531055
Going in the other direction, wrap f_2
in another function to ensure that the function called in the body of the loop always returns a sequence.
for function in [f_1, lambda : (f_2(),)]:
x = function()[0]
The additional overhead of another function call may make this approach undesirable.
Upvotes: 1
Reputation: 1410
I wouldnt go for try-except statement. To me it's an overkill.
More likely I would try to do something like:
result = function()
# this can be changed to abc.Sequence for more general approach
if isinstance(result, (list, tuple)):
result = result[0]
Upvotes: 1