File: validators.py

package info (click to toggle)
python-rebulk 3.3.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 752 kB
  • sloc: python: 7,497; makefile: 3
file content (81 lines) | stat: -rw-r--r-- 1,753 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Validator functions to use in patterns.

All those function have last argument as match, so it's possible to use functools.partial to bind previous arguments.
"""


def chars_before(chars, match):
    """
    Validate the match if left character is in a given sequence.

    :param chars:
    :type chars:
    :param match:
    :type match:
    :return:
    :rtype:
    """
    if match.start <= 0:
        return True
    return match.input_string[match.start - 1] in chars


def chars_after(chars, match):
    """
    Validate the match if right character is in a given sequence.

    :param chars:
    :type chars:
    :param match:
    :type match:
    :return:
    :rtype:
    """
    if match.end >= len(match.input_string):
        return True
    return match.input_string[match.end] in chars


def chars_surround(chars, match):
    """
    Validate the match if surrounding characters are in a given sequence.

    :param chars:
    :type chars:
    :param match:
    :type match:
    :return:
    :rtype:
    """
    return chars_before(chars, match) and chars_after(chars, match)


def validators(*chained_validators):
    """
    Creates a validator chain from several validator functions.

    :param chained_validators:
    :type chained_validators:
    :return:
    :rtype:
    """

    def validator_chain(match):  # pylint:disable=missing-docstring
        for chained_validator in chained_validators:
            if not chained_validator(match):
                return False
        return True

    return validator_chain


def allways_true(match):  # pylint:disable=unused-argument
    """
    A validator which is allways true
    :param match:
    :return:
    """
    return True