Skip to content
Myr

generate_identifier_pattern.py

This file

Path

scripts/generate_identifier_pattern.py

74 lines · 2.0 KiB · Python

Last changed by

Merge branch '3.1.x'David Lordbefore adoption81a2384

History of this file

Take it

The walk stopped after 200 commits: lines older than d3253b0 point at it.

Merge pull request #1307 from pallets/dependabot/pip/pytest-6.1.2dependabot-preview[bot]before adoptiond3253b0

lines 1–31why, one step back
1import itertools
2import 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 """

Merge branch '3.1.x'David Lordbefore adoption81a2384

lines 32–33why, one step back
32 for _, g in itertools.groupby(enumerate(data), lambda x: ord(x[1]) - x[0]):
33 lb = list(g)

fix flake8 bugbear errorDavid Lordbefore adoption090a5a9

line 34why, one step back
34 yield lb[0][1], lb[-1][1]

Merge pull request #1307 from pallets/dependabot/pip/pytest-6.1.2dependabot-preview[bot]before adoptiond3253b0

lines 35–74why, one step back
35
3637def 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 to58 ``jinja2/_identifier.py``.59 """60 pattern = build_pattern(collapse_ranges(get_characters()))61 filename = os.path.abspath(62 os.path.join(os.path.dirname(__file__), "..", "src", "jinja2", "_identifier.py")63 )6465 with open(filename, "w", encoding="utf8") as f:66 f.write("import re\n\n")67 f.write("# generated by scripts/generate_identifier_pattern.py\n")68 f.write("pattern = re.compile(\n")69 f.write(f' r"[\\w{pattern}]+" # noqa: B950\n')70 f.write(")\n")717273if __name__ == "__main__":74 main()