Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return unpacked arguments

Tags:

python

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.

like image 532
Jim K Avatar asked May 18 '26 20:05

Jim K


2 Answers

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
like image 145
ShadowRanger Avatar answered May 20 '26 08:05

ShadowRanger


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.

like image 44
donkopotamus Avatar answered May 20 '26 09:05

donkopotamus