type_coercion
#
Collection of functions to coerce conversion of types with an intelligent guess.
Functions#
|
|
|
Convert a number, string, or sequence type into a pure boolean. |
|
Take a primitive value, usually a string, and try to make a more relevant type out of it. |
|
- numberify(value)#
Examples
>>> [numberify(x) for x in ('1234', 1234, '0755', 0o0755, False, 0, '0', True, 1, '1')] [1234, 1234, 755, 493, 0, 0, 0, 1, 1, 1] >>> [numberify(x) for x in ('12.34', 12.34, 1.2+3.5j, '1.2+3.5j')] [12.34, 12.34, (1.2+3.5j), (1.2+3.5j)]
- boolify(value, nullable=False, return_string=False)#
Convert a number, string, or sequence type into a pure boolean.
- Parameters:
value (number, string, sequence) -- pretty much anything
- Returns:
boolean representation of the given value
- Return type:
Examples
>>> [boolify(x) for x in ('yes', 'no')] [True, False] >>> [boolify(x) for x in (0.1, 0+0j, True, '0', '0.0', '0.1', '2')] [True, False, True, False, False, True, True] >>> [boolify(x) for x in ("true", "yes", "on", "y")] [True, True, True, True] >>> [boolify(x) for x in ("no", "non", "none", "off", "")] [False, False, False, False, False] >>> [boolify(x) for x in ([], set(), dict(), tuple())] [False, False, False, False] >>> [boolify(x) for x in ([1], set([False]), dict({'a': 1}), tuple([2]))] [True, True, True, True]
- typify(value, type_hint=None)#
Take a primitive value, usually a string, and try to make a more relevant type out of it. An optional type_hint will try to coerce the value to that type.
Examples
>>> typify('32') 32 >>> typify('32', float) 32.0 >>> typify('32.0') 32.0 >>> typify('32.0.0') '32.0.0' >>> [typify(x) for x in ('true', 'yes', 'on')] [True, True, True] >>> [typify(x) for x in ('no', 'FALSe', 'off')] [False, False, False] >>> [typify(x) for x in ('none', 'None', None)] [None, None, None]
- maybecall(value)#