简体   繁体   中英

Return unpacked arguments

Is it possible to return unpacked arguments? What I am picturing is to return msg, *msg_args which would return a tuple such as (msg, msg_args[0], msg_args[1], msg_args[2]) . This would allow me to send it to another function for string interpolation.

def add_to_message(msg, *msg_args):
    msg += "  I am %s."
    msg_args = list(msg_args)
    msg_args.append("fine")
    return(msg, *msg_args)

def display_localized_message(msg, *msg_args):
    """Translate message, then interpolate and print it."""
    print(msg % msg_args)

display_localized_message(
    *add_to_message("Hi %s.  How are %s?", "Peter", "you"))

Desired results: print Hi Peter. How are you? I am fine. Hi Peter. How are you? I am fine.

Actual results: SyntaxError: can use starred expression only as assignment target . The line containing the error is return msg, *msg_args .

If you're not using Python 3.5+ with additional unpacking generalizations , you can't unpack as part of a return value. Just explicitly make the combined tuple through tuple concatenation:

return (msg,) + msg_args

In python versions prior to 3.5, simply construct a new tuple using it:

def add_to_message(msg, *msg_args):
    msg += "  I am %s."
    msg_args.append("fine")
    return (msg,) + msg_args

In python 3.5, your current syntax would be fine.

Simple. Just don't use the star and reference as a list.

def add_to_message(msg, *msg_args):
    msg += "  I am %s."
    msg_args.append("fine")
    return (msg,) + msg_args

The * is only used in the method definition to show that it will be a tuple of all of the rest of the arguments. Inside of the method, you reference that tuple without the star. It is just a 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