diff --git a/Lib/pprint.py b/Lib/pprint.py index 7355021998081d..28f8cc85b4ce0b 100644 --- a/Lib/pprint.py +++ b/Lib/pprint.py @@ -39,6 +39,10 @@ import types as _types from io import StringIO as _StringIO +lazy from dataclasses import is_dataclass as _is_dataclass +lazy from dataclasses import fields as _dataclass_fields +lazy import re as _re + __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr", "PrettyPrinter", "pp"] @@ -197,15 +201,14 @@ 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 - from dataclasses import is_dataclass + if p is not None: context[objid] = 1 p(self, object, stream, indent, allowance, context, level + 1) del context[objid] return - elif (is_dataclass(object) and + elif (_is_dataclass(object) and not isinstance(object, type) and object.__dataclass_params__.repr and # Check dataclass has generated repr method. @@ -240,15 +243,12 @@ def _write_indent_padding(self, write): write((self._indent_per_level - 1) * " ") def _pprint_dataclass(self, object, stream, indent, allowance, context, level): - # Lazy import to improve module import time - from dataclasses import fields as dataclass_fields - cls_name = object.__class__.__name__ if self._expand: indent += self._indent_per_level else: indent += len(cls_name) + 1 - items = [(f.name, getattr(object, f.name)) for f in dataclass_fields(object) if f.repr] + items = [(f.name, getattr(object, f.name)) for f in _dataclass_fields(object) if f.repr] stream.write(self._format_block_start(cls_name + '(', indent)) self._format_namespace_items(items, stream, indent, allowance, context, level) stream.write(self._format_block_end(')', indent - self._indent_per_level)) @@ -422,11 +422,8 @@ 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) + parts = _re.findall(r'\S*\s*', line) assert parts assert not parts[-1] parts.pop() # drop empty last part diff --git a/Misc/NEWS.d/next/Library/2026-09-01-23-24-34.gh-issue-154675.hmvwgW.rst b/Misc/NEWS.d/next/Library/2026-09-01-23-24-34.gh-issue-154675.hmvwgW.rst new file mode 100644 index 00000000000000..2bad30fbaf6d28 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-09-01-23-24-34.gh-issue-154675.hmvwgW.rst @@ -0,0 +1 @@ +Use lazy imports instead of inline imports in pprint