CSVResults.render()   F
last analyzed

Complexity

Conditions 12

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
dl 0
loc 28
rs 2.7855
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like CSVResults.render() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
from __future__ import absolute_import
2
3
import csv
4
import operator
5
6
import py
7
8
9
class CSVResults(object):
10
    def __init__(self, columns, sort, logger):
11
        self.columns = columns
12
        self.sort = sort
13
        self.logger = logger
14
15
    def render(self, output_file, groups):
16
        output_file = py.path.local(output_file)
17
        if not output_file.ext:
18
            output_file = output_file.new(ext='csv')
19
        with output_file.open('w', ensure=True) as stream:
20
            writer = csv.writer(stream)
21
            params = sorted(set(
22
                param
23
                for group, benchmarks in groups
24
                for benchmark in benchmarks
25
                for param in benchmark.get("params", {}) or ()
26
            ))
27
            writer.writerow([
28
                "name",
29
            ] + [
30
                "param:{0}".format(p)
31
                for p in params
32
            ] + self.columns)
33
34
            for group, benchmarks in groups:
35
                benchmarks = sorted(benchmarks, key=operator.itemgetter(self.sort))
36
37
                for bench in benchmarks:
38
                    row = [bench.get("fullfunc", bench["fullname"])]
39
                    row.extend(bench.get('params', {}).get(param, "") for param in params)
40
                    row.extend(bench[prop] for prop in self.columns)
41
                    writer.writerow(row)
42
        self.logger.info("Generated csv: {0}".format(output_file), bold=True)
43