benedict.serializers.ini   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 12
eloc 49
dl 0
loc 62
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A INISerializer.encode() 0 13 4
A INISerializer._get_section_option_value() 0 11 3
A INISerializer.decode() 0 15 4
A INISerializer.__init__() 0 4 1
1
from configparser import DEFAULTSECT as default_section
2
from configparser import ConfigParser
3
from io import StringIO
4
5
from benedict.serializers.abstract import AbstractSerializer
6
from benedict.utils import type_util
7
8
9
class INISerializer(AbstractSerializer):
10
    """
11
    This class describes an ini serializer.
12
    """
13
14
    def __init__(self):
15
        super().__init__(
16
            extensions=[
17
                "ini",
18
            ],
19
        )
20
21
    @staticmethod
22
    def _get_section_option_value(parser, section, option):
23
        value = None
24
        funcs = [parser.getint, parser.getfloat, parser.getboolean, parser.get]
25
        for func in funcs:
26
            try:
27
                value = func(section, option)
28
                break
29
            except ValueError:
30
                continue
31
        return value
32
33
    def decode(self, s, **kwargs):
34
        parser = ConfigParser(**kwargs)
35
        parser.read_string(s)
36
        data = {}
37
        for option, _ in parser.defaults().items():
38
            data[option] = self._get_section_option_value(
39
                parser, default_section, option
40
            )
41
        for section in parser.sections():
42
            data[section] = {}
43
            for option, _ in parser.items(section):
44
                data[section][option] = self._get_section_option_value(
45
                    parser, section, option
46
                )
47
        return data
48
49
    def encode(self, d, **kwargs):
50
        parser = ConfigParser(**kwargs)
51
        for key, value in d.items():
52
            if not type_util.is_dict(value):
53
                parser.set(default_section, key, f"{value}")
54
                continue
55
            section = key
56
            parser.add_section(section)
57
            for option_key, option_value in value.items():
58
                parser.set(section, option_key, f"{option_value}")
59
        str_data = StringIO()
60
        parser.write(str_data)
61
        return str_data.getvalue()
62