]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-117865: Defer import of re in ast (#119546)
authorJelle Zijlstra <jelle.zijlstra@gmail.com>
Tue, 28 May 2024 18:04:08 +0000 (11:04 -0700)
committerGitHub <noreply@github.com>
Tue, 28 May 2024 18:04:08 +0000 (11:04 -0700)
This is used only by ast.get_source_segment(), so it seems sensible to avoid importing it.

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Lib/ast.py
Misc/NEWS.d/next/Library/2024-05-25-07-25-07.gh-issue-117865.1A0Xpi.rst [new file with mode: 0644]

index bc6c3347787d6196292338bfc540fb9e12fdcf3c..fb4d21b87d8bd002eb24480d010bc5d1563d0df7 100644 (file)
@@ -25,7 +25,6 @@
     :license: Python License.
 """
 import sys
-import re
 from _ast import *
 from contextlib import contextmanager, nullcontext
 from enum import IntEnum, auto, _simple_enum
@@ -325,12 +324,18 @@ def get_docstring(node, clean=True):
     return text
 
 
-_line_pattern = re.compile(r"(.*?(?:\r\n|\n|\r|$))")
+_line_pattern = None
 def _splitlines_no_ff(source, maxlines=None):
     """Split a string into lines ignoring form feed and other chars.
 
     This mimics how the Python parser splits source code.
     """
+    global _line_pattern
+    if _line_pattern is None:
+        # lazily computed to speedup import time of `ast`
+        import re
+        _line_pattern = re.compile(r"(.*?(?:\r\n|\n|\r|$))")
+
     lines = []
     for lineno, match in enumerate(_line_pattern.finditer(source), 1):
         if maxlines is not None and lineno > maxlines:
diff --git a/Misc/NEWS.d/next/Library/2024-05-25-07-25-07.gh-issue-117865.1A0Xpi.rst b/Misc/NEWS.d/next/Library/2024-05-25-07-25-07.gh-issue-117865.1A0Xpi.rst
new file mode 100644 (file)
index 0000000..48cd390
--- /dev/null
@@ -0,0 +1,2 @@
+Improve the import time of the :mod:`ast` module by deferring the import of
+:mod:`re`. Patch by Jelle Zijlstra.