Passed
Pull Request — master (#496)
by
unknown
02:17
created

annif.transformer   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 57
Duplicated Lines 22.81 %

Importance

Changes 0
Metric Value
eloc 45
dl 13
loc 57
rs 10
c 0
b 0
f 0
wmc 11

3 Functions

Rating   Name   Duplication   Size   Complexity  
A parse_specs() 0 14 3
A get_transform() 0 10 3
A _parse_transform_args() 13 13 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
# TODO Add docstring
2
import re
3
from . import transformer
4
from . import inputlimiter
5
from .transformer import IdentityTransform
6
from annif.exception import ConfigurationException
7
8
__all__ = ["IdentityTransform"]
9
10
11 View Code Duplication
def _parse_transform_args(param_string):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
12
    if not param_string:
13
        return [], {}
14
    kwargs = {}
15
    posargs = []
16
    param_strings = param_string.split(',')
17
    for p_string in param_strings:
18
        parts = p_string.split('=')
19
        if len(parts) == 1:
20
            posargs.append(p_string)
21
        elif len(parts) == 2:
22
            kwargs[parts[0]] = parts[1]
23
    return posargs, kwargs
24
25
26
def parse_specs(transform_specs):
27
    """parse a configuration definition such as 'A(x),B(y=1),C' into a tuples
28
    of ((A, [x], {}), (B, [None], {y: 1}))..."""  # TODO
29
    parsed = []
30
    # Split by commas not inside parentheses
31
    parts = re.split(r',\s*(?![^()]*\))', transform_specs)
32
    for part in parts:
33
        match = re.match(r'(\w+)(\((.*)\))?', part)
34
        if match is None:
35
            continue
36
        transform = match.group(1)
37
        posargs, kwargs = _parse_transform_args(match.group(3))
38
        parsed.append((transform, posargs, kwargs))
39
    return parsed
40
41
42
def get_transform(transform_specs, project):
43
    transform_defs = parse_specs(transform_specs)
44
    transform_classes = []
45
    args = []
46
    for trans, posargs, kwargs in transform_defs:
47
        if trans not in _transforms:
48
            raise ConfigurationException(f"No such transform {trans}")
49
        transform_classes.append(_transforms[trans])
50
        args.append((posargs, kwargs))
51
    return transformer.TransformChain(transform_classes, args, project)
52
53
54
_transforms = {
55
    transformer.IdentityTransform.name: transformer.IdentityTransform,
56
    inputlimiter.InputLimiter.name: inputlimiter.InputLimiter}
57