Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to assign a variable number of returns from a python function

Tags:

python

assign

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)
like image 647
Gabriele Avatar asked Nov 18 '25 04:11

Gabriele


1 Answers

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])
like image 54
Ajax1234 Avatar answered Nov 20 '25 17:11

Ajax1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!