File: _bool.py

package info (click to toggle)
python-typepy 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 624 kB
  • sloc: python: 2,886; makefile: 78; sh: 7
file content (44 lines) | stat: -rw-r--r-- 1,306 bytes parent folder | download | duplicates (2)
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
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""

from .._common import strip_ansi_escape
from .._const import DefaultValue, ParamKey
from ..error import TypeConversionError
from ._interface import AbstractValueConverter


class BoolConverter(AbstractValueConverter):
    def force_convert(self):
        if isinstance(self._value, int):
            return bool(self._value)

        try:
            return self.__strict_strtobool(self._value)
        except ValueError:
            pass

        if self._params.get(ParamKey.STRIP_ANSI_ESCAPE, DefaultValue.STRIP_ANSI_ESCAPE):
            try:
                return self.__strict_strtobool(strip_ansi_escape(self._value))
            except (TypeError, ValueError):
                pass

        raise TypeConversionError(f"failed to force_convert to bool: type={type(self._value)}")

    @staticmethod
    def __strict_strtobool(value):
        if isinstance(value, bool):
            return value

        try:
            lower_text = value.casefold()
        except AttributeError:
            raise ValueError(f"invalid value '{str(value)}'")

        if lower_text in ["true"]:
            return True
        elif lower_text in ["false"]:
            return False

        raise ValueError(f"invalid value '{str(value)}'")