aboutsummaryrefslogtreecommitdiffstats
path: root/config_file/parsers/parse_value.py
blob: 542e2220a6b6c3648fcdb9ad5684457c20e4617d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Parse types allows you to check or parse a string into its native type.

Example:
    parse_value('5') -> 5   (int)
    parse_value('-5') -> -5 (int)

    parse_value('5.52') -> 5.52   (float)
    parse_value('-53.2') -> -53.2 (float)

    parse_value('blahfafda') -> 'blahfafda' (string)

    parse_value('true') -> True (bool)
    parse_value('FALSE') -> False (bool)


"5".isdigit() -> True
"-5".isdigit() -> False
can_be_parsed_as_int("-5") -> True
"""
import re
from distutils.util import strtobool


def parse_value(value):
    if can_be_parsed_as_int(value):
        return int(value)

    if can_be_parsed_as_float(value):
        return float(value)

    if can_be_parsed_as_bool(value):
        return value if type(value) is bool else bool(strtobool(value))

    return value


def can_be_parsed_as_int(value) -> bool:
    if type(value) is int:
        return True

    if type(value) is not str:
        return False

    if value.startswith("-"):
        return value[1:].isdigit()

    return value.isdigit()


def can_be_parsed_as_float(value) -> bool:
    if type(value) is float:
        return True

    if type(value) is not str:
        return False

    if value.startswith("-"):
        return bool(re.match(r"^\d*\.\d+$", value[1:]))

    return bool(re.match(r"^\d*\.\d+$", value))


def can_be_parsed_as_bool(value) -> bool:
    if type(value) is bool:
        return True

    if type(value) is not str:
        return False

    return value.lower() == "true" or value.lower() == "false"