8000 gh-117865: Defer import of re in ast (#119546) · python/cpython@ae11d68 · GitHub
[go: up one dir, main page]

Skip to content

Commit ae11d68

Browse files
gh-117865: Defer import of re in ast (#119546)
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>
1 parent a89fc26 commit ae11d68

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

Lib/ast.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
:license: Python License.
2626
"""
2727
import sys
28-
import re
2928
from _ast import *
3029
from contextlib import contextmanager, nullcontext
3130
from enum import IntEnum, auto, _simple_enum
@@ -325,12 +324,18 @@ def get_docstring(node, clean=True):
325324
return text
326325

327326

328-
_line_pattern = re.compile(r"(.*?(?:\r\n|\n|\r|$))")
327+
_line_pattern = None
329328
def _splitlines_no_ff(source, maxlines=None):
330329
"""Split a string into lines ignoring form feed and other chars.
331330
332331
This mimics how the Python parser splits source code.
333332
"""
333+
global _line_pattern
334+
if _line_pattern is None:
335+
# lazily computed to speedup import time of `ast`
336+
import re
337+
_line_pattern = re.compile(r"(.*?(?:\r\n|\n|\r|$))")
338+
334339
lines = []
335340
for lineno, match in enumerate(_line_pattern.finditer(source), 1):
336341
if maxlines is not None and lineno > maxlines:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve the import time of the :mod:`ast` module by deferring the import of
2+
:mod:`re`. Patch by Jelle Zijlstra.

0 commit comments

Comments
 (0)
0