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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With