Passed
Push — mpeta ( 62640f...eed483 )
by Konstantinos
01:41
created

so_magic.data.filling.StaticDataFiller.__init__()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
from abc import ABC, abstractmethod
2
from functools import reduce
3
import attr
4
import pandas as pd
5
6
from so_magic.utils import SubclassRegistry
7
8
9
class FillerInterface(ABC):
10
    @abstractmethod
11
    def fill(self, *args, **kwargs):
12
        raise NotImplementedError
13
14
15
class FillerFactoryType(type):
16
17
    @classmethod
18
    def create(mcs, *args, **kwargs) -> FillerInterface:
19
        raise NotImplementedError
20
21
22
class FillerFactoryClassRegistry(metaclass=SubclassRegistry): pass
23
24
25
@FillerFactoryClassRegistry.register_as_subclass('static')
26
class StaticDataFiller(FillerInterface):
27
    def __init__(self, *args, **kwargs) -> None:
28
        self._variable = args[1]
29
        if callable(kwargs.get('value')):
30
            self._fct = kwargs['value']
31
        else:
32
            self._fct = self._variable.data_type
33
            print('\n----->', self._fct, type(self._fct))
34
35
    def replace_missing_with_true_zero(self, value, true_zero):
36
        try:
37
            if pd.isnull(value):  # True for both np.nan and None
38
                return true_zero
39
        except ValueError:
40
            pass
41
        return value
42
43
    def fill(self, *args, **kwargs):
44
        datapoints = args[0]
45
        datapoints.observations[str(self._variable)] = datapoints.observations[str(self._variable)].map(lambda a: self.replace_missing_with_true_zero(a, self._fct()))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable str does not seem to be defined.
Loading history...
46
47
48
@attr.s
49
class FillerFactory:
50
    filler_factory_classes_registry = attr.ib(default=attr.Factory(lambda: FillerFactoryClassRegistry))
51
    def create(self, datapoints, variable, value=None):
52
        key = 'static'
53
        return self.filler_factory_classes_registry.create(key, datapoints, variable, value=value)
54
55
56
@attr.s
57
class MagicFillerFactory:
58
    filler_factory = attr.ib(init=False, default=attr.Factory(FillerFactory))
59
60
    def create(self, datapoints, variable, value=None):
61
        return self.filler_factory.create(datapoints, variable, value=value)
62