From 6c4e1738e2fc6f1c6872d7729c72d79457c62c1e Mon Sep 17 00:00:00 2001 From: Daniel Hollas Date: Sun, 10 Dec 2023 02:03:15 +0000 Subject: [PATCH 1/2] Speed up import time of logging module Delayed import of traceback results in ~16% speedup. Issue #109653 --- Lib/logging/__init__.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py index eb7e020d1edfc0..d8cfe9400012f4 100644 --- a/Lib/logging/__init__.py +++ b/Lib/logging/__init__.py @@ -23,7 +23,10 @@ To use, simply 'import logging' and log away! """ -import sys, os, time, io, re, traceback, warnings, weakref, collections.abc +import sys, os, time, io, re, warnings, weakref, collections.abc + +# Speed up import time by delaying traceback import until needed +traceback = None from types import GenericAlias from string import Template @@ -653,6 +656,9 @@ def formatException(self, ei): This default implementation just uses traceback.print_exception() """ + global traceback + if traceback is None: + import traceback sio = io.StringIO() tb = ei[2] # See issues #9427, #1553375. Commented out for now. @@ -1061,6 +1067,9 @@ def handleError(self, record): The record which was being processed is passed in to this method. """ if raiseExceptions and sys.stderr: # see issue 13807 + global traceback + if traceback is None: + import traceback exc = sys.exception() try: sys.stderr.write('--- Logging error ---\n') @@ -1601,6 +1610,9 @@ def findCaller(self, stack_info=False, stacklevel=1): co = f.f_code sinfo = None if stack_info: + global traceback + if traceback is None: + import traceback with io.StringIO() as sio: sio.write("Stack (most recent call last):\n") traceback.print_stack(f, file=sio) From 5ae66a224d971c34df274b2dd544c846d762a592 Mon Sep 17 00:00:00 2001 From: Daniel Hollas Date: Tue, 12 Dec 2023 08:46:01 +0000 Subject: [PATCH 2/2] Add NEWS entry --- .../next/Library/2023-12-12-08-44-30.gh-issue-109653.ZCUa8H.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2023-12-12-08-44-30.gh-issue-109653.ZCUa8H.rst diff --git a/Misc/NEWS.d/next/Library/2023-12-12-08-44-30.gh-issue-109653.ZCUa8H.rst b/Misc/NEWS.d/next/Library/2023-12-12-08-44-30.gh-issue-109653.ZCUa8H.rst new file mode 100644 index 00000000000000..847f03f9048220 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2023-12-12-08-44-30.gh-issue-109653.ZCUa8H.rst @@ -0,0 +1 @@ +Reduce the import time of :mod:`logging` module by ~15%. Patch by Daniel Hollas.