I'm using a python library with a function returning results as a list. Depending on the experiment configuration, this list is made of one or two elements. In this case, a straightforward way to assign the function output is the following:
bbox, segm = None, None
results = test_model() # returns a list with either one or two elements
bbox = results[0]
if len(results) > 1:
segm = results[1]
# [some other code here]
if segm is not None:
plot(segm)
However, this seems to be quite verbose because we need to first initialise both bbox and segm to None, and then evaluate if len(results) > 1. Is there any pythonic way to avoid this? Ideally, something like this would be very nice:
bbox, segm = test_model() # returns a list with either one or two elements
if segm is not None:
plot(segm)
You can use structural pattern matching, available in Python 3.10:
match test_model():
case [bbox, segm]:
plot(segm)
case bbox:
pass
However, if test_module always returns a tuple, you can use unpacking:
bbox, *segm = test_model()
Now, if text_model returned one value, segm will be an empty list ([]). However, if it returned two values, segm will contain a single element. Thus, your full code can become:
bbox, *segm = test_model()
if segm:
plot(segm[0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With