Jim K
Jim K

Reputation: 13790

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.

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

Upvotes: 3

Views: 1482

Answers (3)

Alex K
Alex K

Reputation: 8338

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.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155363

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

Upvotes: 3

donkopotamus
donkopotamus

Reputation: 23176

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.

Upvotes: 1

Related Questions