[Python-ideas] kwargs for return

Steven D'Aprano steve at pearwood.info
Sat Jan 26 19:01:05 EST 2019


On Sat, Jan 26, 2019 at 10:20:11AM -0800, Christopher Barker wrote:

> My first thought was that function return tuples, so you could document
> that your function should be called as such:
> 
> x = fun()[0]
> 
> but, alas, tuple unpacking is apparently automatically disabled for single
> value tuples  (how do you distinguish a tuple with a single value and the
> value itself??)

The time machine strikes again. We have not one but THREE ways of doing 
so (although two are alternate ways of spelling the same thing):

py> def func():
...     return [1]
...
py> (spam,) = func()  # use a 1-element tuple on the left
py> [spam] = func()  # or a list
py> spam
1

py> spam, *ignore = func()
py> spam
1
py> ignore
[]


But if you're extracting a single value using subscripting on the right 
hand side, you don't need anything so fancy:

py> eggs = func()[0]  # doesn't matter how many items func returns
py> eggs
1




-- 
Steve


More information about the Python-ideas mailing list