From 6919c19ed4fa14180bbbdc88f98813f4215b29a2 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Date: Mon, 5 Aug 2024 17:40:43 +0300 Subject: [PATCH] Improve import time of pprint --- Lib/pprint.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Lib/pprint.py b/Lib/pprint.py index 9314701db340c78..afc83d0e12ee7ab 100644 --- a/Lib/pprint.py +++ b/Lib/pprint.py @@ -35,8 +35,6 @@ """ import collections as _collections -import dataclasses as _dataclasses -import re import sys as _sys import types as _types from io import StringIO as _StringIO @@ -179,6 +177,9 @@ def _format(self, object, stream, indent, allowance, context, level): max_width = self._width - indent - allowance if len(rep) > max_width: p = self._dispatch.get(type(object).__repr__, None) + # Lazy import to improve module import time + import dataclasses as _dataclasses + if p is not None: context[objid] = 1 p(self, object, stream, indent, allowance, context, level + 1) @@ -197,6 +198,9 @@ def _format(self, object, stream, indent, allowance, context, level): stream.write(rep) def _pprint_dataclass(self, object, stream, indent, allowance, context, level): + # Lazy import to improve module import time + import dataclasses as _dataclasses + cls_name = object.__class__.__name__ indent += len(cls_name) + 1 items = [(f.name, getattr(object, f.name)) for f in _dataclasses.fields(object) if f.repr] @@ -291,6 +295,9 @@ def _pprint_str(self, object, stream, indent, allowance, context, level): if len(rep) <= max_width1: chunks.append(rep) else: + # Lazy import to improve module import time + import re + # A list of alternating (non-space, space) strings parts = re.findall(r'\S*\s*', line) assert parts