list slice and generators

Pavlos Parissis pavlos.parissis at gmail.com
Tue Nov 24 16:38:22 EST 2015


Hi,

Do you see any possible dangerous hidden bug in the below code(using
python2.7 and python3.4)?

My goal is to avoid go through the metrics list twice. But, I don't
know if there will be a problem with doing in place replace of list
elements using 2 generators.

# metrics = ['', '0', '10'....]
metrics = [x.metric(name) for x in self._server_per_proc]
metrics[:] = (converter(x) for x in metrics)
metrics[:] = (x for x in metrics if x is not None)

return calculate(name, metrics)


def calculate(name, metrics):
     if not metrics:
        return None

    if name in METRICS_SUM:
        return sum(metrics)
    elif name in METRICS_AVG:
        return int(sum(metrics)/len(metrics))
    else:
        raise ValueError("Unknown type of calculation for {}".format(name))


def converter(value):
    try:
        return int(float(value))
    except ValueError:
        return value.strip() or None
    except TypeError:
        return None


Cheers,
Pavlos

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20151124/3075c5fa/attachment.sig>


More information about the Python-list mailing list