for loop over function that returns a tuple?

Steven D'Aprano steve at
Wed Sep 2 18:09:05 CEST 2015

On Wed, 2 Sep 2015 09:49 pm, Victor Hooi wrote:

> 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))
> I also have:
>     def create_point(timestamp, metric_name, values, tags):
>         return {
>             "measurement": _MEASUREMENT_PREFIX + metric_name,
>             "tags": tags,
>             "time": timestamp,
>             "fields": values
>         }
> 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))

Ah, now I see what's happening!

Sorry for being so dim, I thought that get_metrics returned a list or
sequence of tuples:

    [(timestamp, "serverstatus", values, tags),
     (timestamp, "serverstatus", values, tags),
     (timestamp, "serverstatus", values, tags)]

and you were iterating over the list, so that each time you would get a
tuple of four values:

    metric_data = (timestamp, "serverstatus", values, tags)

which you can then pass to create_point:


So you confused me by saying that metric_data held only the timestamp. But
now I see that I was mistaken, and you are doing this:

    for metric_data in get_metrics( ... ):  # returns a single tuple
        # first time through the loop, metric_data = timestamp;
        # second time through the loop, metric_data = "serverstatus"
        # third time through the loop, metric_data = values
        # final time through the loop, metric_data = tags

Get rid of the loop, and write this:

metric_data = get_metrics(server_status_json, mmapv1_metrics, line_number)


More information about the Python-list mailing list