Skip to content

Commit 9cbb64c

Browse files
committed
pythongh-117865: Defer import of re in ast
This is used only by ast.get_source_segment(), so it seems sensible to avoid importing it.
1 parent b48a3db commit 9cbb64c

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

Lib/ast.py

Lines changed: 6 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,17 @@ 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+
import re
336+
_line_pattern = re.compile(r"(.*?(?:\r\n|\n|\r|$))")
337+
334338
lines = []
335339
for lineno, match in enumerate(_line_pattern.finditer(source), 1):
336340
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)