Style qeustion: Multiple return values

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Mon Apr 12 13:41:34 EDT 2021


On 2021-04-12 at 09:54:13 -0700,
Dan Stromberg <drsalists at gmail.com> wrote:

> On Mon, Apr 12, 2021 at 1:30 AM Steve Keller <keller.steve at gmx.de> wrote:
> 
> > Just a short style question: When returning multiple return values, do
> > you use parenthesis?
> >
> > E.g. would you write
> >
> >     def foo():
> >         return 1, 2
> >
> >     a, b = foo()
> >
> > or do you prefer
> >
> >     def foo():
> >         return (1, 2)
> >
> >     (a, b) = foo()
> >
> 
> I prefer the parens; it's too easy to miss a comma when reading.   The
> parentheses make it more clear that you're looking at a tuple.

If I were to write it like this:

    a,b = foo()

rather than like this:

    a, b = foo()

then I might agree that the comma might be mistakable for a dot or even
"disappear" altogether.  To the compiler, the extraneous space doesn't
matter, but to a human reader, it makes a huge difference.

That said, consider this function:

    def f(*args):
        whatever()

Do you prefer f(a, b) or f((a, b))?

Okay, so it's a trick question, but that's how I think about *returning*
multiple values, too:  "a, b" is two values, but "(a, b)" is one value
that happens to be a tuple.

Lastly, with names like foo, a, and b, we might be misfocused.  Does any
of this change with names like coordinate, account_number, or distance?
Do meaningful names help, or do they merely distract from the commas and
the parentheses?

    (x_coord, y_coord) = locate_target(parameters)
    likely_name, probability = best_match(parameters)


More information about the Python-list mailing list