File: genboolean.py

package info (click to toggle)
treeline 3.1.5-1.1
  • links: PTS
  • area: main
  • in suites: trixie
  • size: 6,508 kB
  • sloc: python: 20,489; javascript: 998; makefile: 54
file content (128 lines) | stat: -rw-r--r-- 4,017 bytes parent folder | download | duplicates (3)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/bin/env python3

#******************************************************************************
# genboolean.py, provides a class for boolean formating
#
# Copyright (C) 2018, Douglas W. Bell
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License, either Version 2 or any later
# version.  This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY.  See the included LICENSE file for details.
#******************************************************************************

import re


_formatDict = {N_('true'):True, N_('false'):False,
               N_('yes'):True, N_('no'):False}
for key, value in _formatDict.copy().items():
    _formatDict[key[0]] = value
    _formatDict[_(key)] = value
    _formatDict[_(key)[0]] = value

class GenBoolean:
    """Class to store & format boolean values.

    Uses a simple format of <true>/<false>.
    """
    def __init__(self, boolStr='true'):
        """Initialize a GenBoolean object with any format from _formatDict.
        
        Raises ValueError with an inappropriate argument.
        Arguments:
            boolStr -- the string to evaluate
        """
        self.setBool(boolStr)

    def setBool(self, boolStr):
        """Initialize a GenBoolean object with any format from _formatDict.
        
        Raises ValueError with an inappropriate argument.
        Arguments:
            boolStr -- the string to evaluate
        """
        try:
            self.value = _formatDict[boolStr.lower()]
        except KeyError:
            raise ValueError

    def setFromStr(self, boolStr, strFormat='yes/no'):
        """Set boolean value based on given format string.

        Raises ValueError with an inappropriate argument.
        Returns self.
        Arguments:
            boolStr -- the string to evaluate
            strFormat -- a text format in True/False style
        """
        try:
            self.value = self.customFormatDict(strFormat)[boolStr.lower()]
        except KeyError:
            raise ValueError
        return self

    @staticmethod
    def customFormatDict(strFormat):
        """Return a dictionary based on the format.

        The dictionary includes conversions in both directions.
        String keys are in lower case.
        Double editSep's are not split (become single).
        Raises ValueError with an inappropriate format.
        Arguments:
            strFormat -- a text format in True/False style
        """
        strFormat = strFormat.replace('//', '\0')
        trueVal, falseVal = strFormat.split('/', 1)
        trueVal = trueVal.replace('\0', '/')
        falseVal = falseVal.replace('\0', '/')
        if not trueVal or not falseVal or trueVal == falseVal:
            raise ValueError
        return {trueVal.lower():True, falseVal.lower():False,
                True:trueVal, False:falseVal}

    def boolStr(self, strFormat='yes/no'):
        """Return the boolean string in the given strFormat.

        Arguments:
        Format:
            strFormat -- a text format in True/False style
        """
        return self.customFormatDict(strFormat)[self.value]

    def clone(self):
        """Return cloned instance.
        """
        return self.__class__(self.value)

    def __repr__(self):
        """Outputs in general string fomat.
        """
        return repr(self.value)

    def __eq__(self, other):
        """Equality test.
        """
        try:
            return self.value == other.value
        except AttributeError:
            return self.value == other

    def __ne__(self, other):
        """Non-equality test.
        """
        try:
            return self.value != other.value
        except AttributeError:
            return self.value != other

    def __hash__(self):
        """Allow use as dictionary key.
        """
        return hash(self.value)

    def __nonzero(self):
        """Allow truth testing.
        """
        return self.value