for loop over function that returns a tuple?

Jussi Piitulainen harvesting at makes.address.invalid
Wed Sep 2 08:24:28 EDT 2015


Victor Hooi writes:

> I have a function which is meant to return a tuple:
>
>     def get_metrics(server_status_json, metrics_to_extract, line_number):
>         <SOME_CODE>
>         return ((timestamp, "serverstatus", values, tags))

That returns a single tuple of four values. The double parentheses are
redundant.

> I also have:
>
>     def create_point(timestamp, metric_name, values, tags):

That can take the four values in the tuple returned by get_metrics, ok.

> I am calling get_metric in a for loop like so:
>
>     for metric_data in get_metrics(server_status_json, mmapv1_metrics, line_number):
>         json_points.append(create_point(*metric_data))

That sets metric_data to each of the four values in the one tuple in
turn. You seem to want just:

    json_points.append(create_point(*get_metrics(...)))

> I was hoping to use tuple unpacking to pass metric_data straight from
> get_metrics through to create_point.

That should be cool. It's the loop that's a little bit too much. (If you
want get_metrics to return a singleton tuple containing the four-tuple,
you need an extra comma in there: (x) is just x; (x,) is a tuple
containing x.



More information about the Python-list mailing list