Skip to content
Myr

generate_identifier_pattern.py

This file

Path

scripts/generate_identifier_pattern.py

73 lines · 2.1 KiB · Python

Last changed by

update identifier pattern for Python 3.10 (#2099)David Lordbefore adoption1030482

History of this file

Take it

1import itertools2import os3import re4import sys567def get_characters():8    """Find every Unicode character that is valid in a Python `identifier`_ but9    is not matched by the regex ``\\w`` group.1011    ``\\w`` matches some characters that aren't valid in identifiers, but12    :meth:`str.isidentifier` will catch that later in lexing.1314    All start characters are valid continue characters, so we only test for15    continue characters.1617    _identifier: https://docs.python.org/3/reference/lexical_analysis.html#identifiers18    """19    for cp in range(sys.maxunicode + 1):20        s = chr(cp)2122        if ("a" + s).isidentifier() and not re.match(r"\w", s):23            yield s242526def collapse_ranges(data):27    """Given a sorted list of unique characters, generate ranges representing28    sequential code points.2930    Source: https://stackoverflow.com/a/4629241/40061731    """32    for _, g in itertools.groupby(enumerate(data), lambda x: ord(x[1]) - x[0]):33        lb = list(g)34        yield lb[0][1], lb[-1][1]353637def build_pattern(ranges):38    """Output the regex pattern for ranges of characters.3940    One and two character ranges output the individual characters.41    """42    out = []4344    for a, b in ranges:45        if a == b:  # single char46            out.append(a)47        elif ord(b) - ord(a) == 1:  # two chars, range is redundant48            out.append(a)49            out.append(b)50        else:51            out.append(f"{a}-{b}")5253    return "".join(out)545556def main():57    """Build the regex pattern and write it to ``jinja2/_identifier.py``."""58    pattern = build_pattern(collapse_ranges(get_characters()))59    filename = os.path.abspath(60        os.path.join(os.path.dirname(__file__), "..", "src", "jinja2", "_identifier.py")61    )6263    with open(filename, "w", encoding="utf8") as f:64        f.write("# generated by scripts/generate_identifier_pattern.py")65        f.write(f"# Python {sys.version_info[0]}.{sys.version_info[1]}\n")66        f.write("import re\n\n")67        f.write("pattern = re.compile(\n")68        f.write(f'    r"[\\w{pattern}]+"  # noqa: B950\n')69        f.write(")\n")707172if __name__ == "__main__":73    main()