|
1
|
|
|
# -*- coding: utf-8 -*- |
|
2
|
|
|
|
|
3
|
1 |
|
import six |
|
4
|
|
|
|
|
5
|
|
|
""" |
|
6
|
|
|
Type-conversion helpers |
|
7
|
|
|
|
|
8
|
|
|
This module contains several classes and functions for parsing and converting |
|
9
|
|
|
types. |
|
10
|
|
|
|
|
11
|
|
|
Most functions are designed to work like default functions: :class:`int` |
|
12
|
|
|
:class:`bool` --- take at least one parameter and return well-typed value. |
|
13
|
|
|
""" |
|
14
|
|
|
|
|
15
|
|
|
|
|
16
|
1 |
|
def str2bool(strvalue, default=None): |
|
17
|
|
|
""" |
|
18
|
|
|
Converts string value to :class:`bool`. Can parse human-readable values, |
|
19
|
|
|
like ``'yes'`` and ``'off'``. |
|
20
|
|
|
|
|
21
|
|
|
If value is not recognized -- the value of the :paramref:`~str2bool.default` |
|
22
|
|
|
argument will be returned. |
|
23
|
|
|
|
|
24
|
|
|
.. note:: |
|
25
|
|
|
|
|
26
|
|
|
:func:`str2bool` is not an extension of default :class:`bool`. For |
|
27
|
|
|
example, it doesn't recognize integer ``2`` (or any other number) as |
|
28
|
|
|
:data:`True` value. |
|
29
|
|
|
|
|
30
|
|
|
:param strvalue: Value to parse |
|
31
|
|
|
:type strvalue: str |
|
32
|
|
|
:param default: Default value, defaults to :data:`None` |
|
33
|
|
|
:type default: * |
|
34
|
|
|
:returns: Parsed boolean value or :paramref:`~str2bool.default` \ |
|
35
|
|
|
(if defined). Not a bool value will be returned **only** if value was not \ |
|
36
|
|
|
recognized. |
|
37
|
|
|
:rtype: bool or * |
|
38
|
|
|
|
|
39
|
|
|
""" |
|
40
|
1 |
|
if strvalue is None: |
|
41
|
1 |
|
return default |
|
42
|
|
|
|
|
43
|
1 |
|
rl = str(strvalue).lower() |
|
44
|
1 |
|
if rl in ['true', '1', 't', 'y', 'yes', 'on']: |
|
45
|
1 |
|
return True |
|
46
|
1 |
|
if rl in ['false', '0', 'f', 'n', 'no', 'off']: |
|
47
|
1 |
|
return False |
|
48
|
|
|
|
|
49
|
1 |
|
return default |
|
50
|
|
|
|
|
51
|
|
|
|
|
52
|
1 |
|
def bool201(boolvalue): |
|
53
|
|
|
""" |
|
54
|
|
|
Converts :class:`bool` value to string: ``u'0'`` or ``u'1'`` --- a returned |
|
55
|
|
|
value is in unicode. |
|
56
|
|
|
|
|
57
|
|
|
:param boolvalue: Value to convert |
|
58
|
|
|
:type boolvalue: bool |
|
59
|
|
|
:returns: String ``'0'`` or ``'1'`` |
|
60
|
|
|
:rtype: str |
|
61
|
|
|
:raises TypeError: if not a bool argument was passed |
|
62
|
|
|
""" |
|
63
|
1 |
|
if not isinstance(boolvalue, bool): |
|
64
|
1 |
|
raise TypeError('bool expected') |
|
65
|
|
|
|
|
66
|
1 |
|
if boolvalue: |
|
67
|
1 |
|
return six.text_type('1') |
|
68
|
|
|
return six.text_type('0') |
|
69
|
|
|
|