field_to_ini()   B
last analyzed

Complexity

Conditions 5

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 0
cts 0
cp 0
rs 8.5454
cc 5
crap 30
1
# coding: utf-8
2
3 1
from schematics.types import StringType, IntType, FloatType, BooleanType
4
5 1
from il2fb.config.ds.compat import configparser
6
7
8 1
_NO_VALUE = object()
9 1
_TYPE_TO_GETTER_MAP = {
10
    StringType: 'get',
11
    IntType: 'getint',
12
    FloatType: 'getfloat',
13
    BooleanType: 'getboolean',
14
}
15
16
17 1
def _get_getter(class_type, ini):
18
    try:
19
        method_name = _TYPE_TO_GETTER_MAP.get(class_type)
20
        return getattr(ini, method_name)
21
    except Exception:
22
        return ini.get
23
24
25 1
def field_from_ini(field, ini, section, option, default=_NO_VALUE):
26
    getter = _get_getter(field.typeclass, ini)
27
    try:
28
        return getter(section, option)
29
    except (configparser.NoSectionError, configparser.NoOptionError):
30
        return (
31
            default
32
            if default is not _NO_VALUE else
33
            field.default
34
        )
35
36
37
def field_to_ini(field_value, ini, section, option):
38
    if not ini.has_section(section):
39
        ini.add_section(section)
40
41
    if isinstance(field_value, bool):
42
        field_value = 1 if field_value else 0
43
    elif isinstance(field_value, float):
44
        field_value = round(field_value, 2)
45
46
    ini[section][option] = str(field_value)
47