[Python-ideas] bool.from_config_str()

Terry Reedy tjreedy at udel.edu
Sun Jun 12 23:10:05 EDT 2016


On 6/12/2016 7:52 PM, jab at math.brown.edu wrote:
> Dear Python-Ideas,
>
> (New here... hope this idea contributes something!)
>
> Several times I've had to implement a silly function that converts the
> odd environment variable (or some other value from the outside world
> that, perforce, comes in as a string) to the boolean it actually
> represents.
>
> I say "silly" because, for other commonly-needed types of primitive
> values, we have concise, idiomatic ways to convert them from strings,
> leaving no need for wheel reinvention:
>
> int(os.getenv('NUM_FJORDS'))
> float(os.getenv('PRICE_LIMBURGER'))
> etc.
>
> So I thought it might be nice if we could do something like this for
> booleans, too:

We already can, with much more flexibility.  See below.

> Python 3.6.0a1+ (default:0b18f7d262cc+, Jun 12 2016, 18:21:54)
> [GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> bool.from_config_str('false')
> False
>>>> bool.from_config_str('False')
> False
>>>> bool.from_config_str('True')
> True
>>>> bool.from_config_str('true')
> True

This is all specific to English.

>>>> bool.from_config_str('0')
> False

Duplicates bool(int('0')).  Ditto for '1'.

>>>> bool.from_config_str('')
> False

Duplicates bool('').

>>>> bool.from_config_str('1')
> True

These collectively duplicate "s in {'True', 'true', '1'}"
One can use any set of strings to be mapped to True.  The set can be 
reduced by lowercasing s. For an entry form, one might convert with
"man = sex.lower() in {'m', 'man', 'male'}".  One might even decide that 
"man = sex.lower.beginswith('m') is good enough.

For standard .cfg configuration files, configparser.RawConfigParser has 
this class attribute and method.

# Possible boolean values in the configuration.
BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
                   '0': False, 'no': False, 'false': False, 'off': False}

def _convert_to_boolean(self, value):
     """Return a boolean value translating from other types if necessary.
     """
     if value.lower() not in self.BOOLEAN_STATES:
         raise ValueError('Not a boolean: %s' % value)
     return self.BOOLEAN_STATES[value.lower()]


One can customize this for any langauge or application.  A bool function 
would need duplicate attribute.


-- 
Terry Jan Reedy



More information about the Python-ideas mailing list