Quantcast
Channel: Python – Mischiefblog
Viewing all articles
Browse latest Browse all 11

Unpacking sequences in Python when used as function arguments

$
0
0

D’oh. Next time, I’ll just search the docs instead of thrusting blindly forward in an inefficient direction.

See 4.7.4 Unpacking Argument Lists in the Python Tutorial. It just goes to show that even when you think you know a language pretty well, there’s always something new to learn, especially if it’s a language feature you haven’t used before.

Instead of doing this:

values = self.get_field_values()
 
# build the value string
value_str = ''
 
for value in values:
    if len(value_str) > 0:
        value_str += ','
    if isinstance(value, str):
        value = replace("'", "''")
        value_str += "'" + value + "'"
    else:
        value_str += str(value)
 
result = eval("somefunc(" + value_str + ")")

you can simply do this:

somefunc(*values)

and Python will unpack the sequence into an argument list.


Viewing all articles
Browse latest Browse all 11

Trending Articles