1
"""Custom converters for :mod:`attrs`."""
2

3

4 4
def value_or_none(converter):
5
    """Make converter that returns value or ``None``.
6

7
    ``converter`` is called to further convert non-``None`` values.
8

9
    This converter is identical to :func:`attr.converters.optional` in attrs >=
10
    17.1.0.
11
    """
12

13 4
    def value_or_none_converter(value):
14 4
        if value is None:
15 4
            return None
16 4
        return converter(value)
17

18 4
    return value_or_none_converter
19

20

21 4
def truthy_or_none(converter):
22
    """Make converter that returns a truthy value or ``None``.
23

24
    ``converter`` is called to further convert non-``None`` values.
25
    """
26

27 4
    def truthy_or_none_converter(value):
28 4
        if not value:
29 4
            return None
30 4
        return converter(value)
31

32 4
    return truthy_or_none_converter
33

34

35 4
def stripped_spaces_around(converter):
36
    """Make converter that strippes leading and trailing spaces.
37

38
    ``converter`` is called to further convert non-``None`` values.
39
    """
40

41 4
    def stripped_text_converter(value):
42 4
        if value is None:
43 0
            return None
44 4
        return converter(value.strip())
45

46 4
    return stripped_text_converter
47

48

49 4
def stripped_newlines(converter):
50
    """Make converter that returns a string stripped of newlines or ``None``.
51

52
    ``converter`` is called to further convert non-``None`` values.
53
    """
54

55 4
    def single_line_converter(value):
56 4
        if value is None:
57 0
            return None
58 4
        return converter(value.replace('\r', '').replace('\n', ''))
59

60 4
    return single_line_converter
61

62

63 4
def fixed_len_str(length, converter):
64
    """Make converter that pads a string to the given ``length`` or ``None``.
65

66
    ``converter`` is called to further converti non-``None`` values.
67
    """
68

69 4
    def fixed_len_str_converter(value):
70 4
        if value is None:
71 0
            return None
72 4
        return converter('{value:{length}}'.format(value=value, length=length))
73

74 4
    return fixed_len_str_converter

Read our documentation on viewing source code .

Loading