简体   繁体   中英

starred return statements in Python

My question is regarding the following code:

def foo(*args):
    return *args # syntax error

def bar(*args):
    return 0, *args # ok

def foobar(*args):
    if len(args) == 1:
        return args[0]
    return args

print(bar(1,2))
print(foobar(1,2))
print(foobar(1))

>>> (0,1,2)
>>> (1,2)
>>> 1

is there why reason why foo , rather than being invalid Python code, does not have the same behaviour as foobar ? I guess I would also be willing to accept foo producing a singleton tuple ie (1,) = foo(1) . Any insight into this would be appreciated!

With regards to the explanation, I believe the comments made above have addressed it. I wrote the following code and got it to return (1,). You can also follow the suggestion and simply remove the * in front of args in your original code as the comments suggest.

def foo(*args):
    return *args, 

def bar(*args):
    return 0, *args # ok

def foobar(*args):
    if len(args) == 1:
        return args[0]
    return args

print(bar(1,2))
print(foobar(1,2))
print(foobar(1))
print(foo(1))

Here is a picture of the output. I am using Python 3.8 在此处输入图像描述

It returns the singleton tuple, as you desire. Is this what you needed?

As mentioned in the comments, usefulness of such construct is rather dubious. Esp. since you end up returning tuple of unpacked values... so why not return the tuple itself?

If you really wanted to make this work, you could, starting with Python 3.5 say:

return (*args,)

In line with PEP-448 . This unpacks args items into tuple that is to be returned.

And starting with Python 3.8 , you could drop the enclosing parenthesis:

Generalized iterable unpacking in yield and return statements no longer requires enclosing parentheses...

return *args,

Your bar() does essentially the same using that generalized unpacking behavior as described in the linked PEP, just having leading item in the tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM