Skip to content

gh-118761: Improve import time by lazy import of warnings #129765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Lib/codeop.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
"""

import __future__
import warnings

_features = [getattr(__future__, fname)
for fname in __future__.all_feature_names]
Expand All @@ -57,6 +56,8 @@ def _maybe_compile(compiler, source, filename, symbol):
if symbol != "eval":
source = "pass" # Replace it with a 'pass' statement

import warnings

# Disable compiler warnings when checking for incomplete input.
with warnings.catch_warnings():
warnings.simplefilter("ignore", (SyntaxWarning, DeprecationWarning))
Expand Down
2 changes: 0 additions & 2 deletions Lib/ctypes/_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
"""

import sys
import warnings
import struct

from _ctypes import CField, buffer_info
import ctypes
Expand Down
11 changes: 6 additions & 5 deletions Lib/hmac.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
Implements the HMAC algorithm as described by RFC 2104.
"""

import warnings as _warnings
try:
import _hashlib as _hashopenssl
except ImportError:
Expand Down Expand Up @@ -81,15 +80,17 @@ def _init_old(self, key, msg, digestmod):
self._inner = digest_cons()
self.digest_size = self._inner.digest_size

import warnings

if hasattr(self._inner, 'block_size'):
blocksize = self._inner.block_size
if blocksize < 16:
_warnings.warn('block_size of %d seems too small; using our '
'default of %d.' % (blocksize, self.blocksize),
RuntimeWarning, 2)
warnings.warn('block_size of %d seems too small; using our '
'default of %d.' % (blocksize, self.blocksize),
RuntimeWarning, 2)
blocksize = self.blocksize
else:
_warnings.warn('No block_size attribute on given digest object; '
warnings.warn('No block_size attribute on given digest object; '
'Assuming %d.' % (self.blocksize),
RuntimeWarning, 2)
blocksize = self.blocksize
Expand Down
2 changes: 1 addition & 1 deletion Lib/importlib/metadata/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import zipfile
import operator
import textwrap
import warnings
import functools
import itertools
import posixpath
Expand Down Expand Up @@ -341,6 +340,7 @@ def __new__(cls, *args, **kwargs):
if getattr(getattr(cls, name), '__isabstractmethod__', False)
}
if abstract:
import warnings
warnings.warn(
f"Unimplemented abstract methods {abstract}",
DeprecationWarning,
Expand Down
2 changes: 1 addition & 1 deletion Lib/importlib/resources/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import types
import importlib
import inspect
import warnings
import itertools

from typing import Union, Optional, cast
Expand Down Expand Up @@ -35,6 +34,7 @@ def wrapper(anchor=undefined, package=undefined):
if package is not undefined:
if anchor is not undefined:
return func(anchor, package)
import warnings
warnings.warn(
"First parameter to files is renamed to 'anchor'",
DeprecationWarning,
Expand Down
3 changes: 1 addition & 2 deletions Lib/importlib/resources/_functional.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""Simplified function-based API for importlib.resources"""

import warnings

from ._common import files, as_file


Expand Down Expand Up @@ -51,6 +49,7 @@ def contents(anchor, *path_names):
The iterable returns :class:`str` resources (e.g. files).
The iterable does not recurse into subdirectories.
"""
import warnings
warnings.warn(
"importlib.resources.contents is deprecated. "
"Use files(anchor).iterdir() instead.",
Expand Down
2 changes: 1 addition & 1 deletion Lib/importlib/resources/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import pathlib
import operator
import re
import warnings
import zipfile
from collections.abc import Iterator

Expand Down Expand Up @@ -194,6 +193,7 @@ def _ensure_traversable(path):
if not isinstance(path, str):
return path

import warnings
warnings.warn(
"String arguments are deprecated. Pass a Traversable instead.",
DeprecationWarning,
Expand Down
8 changes: 7 additions & 1 deletion Lib/logging/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
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, traceback, weakref, collections.abc

from types import GenericAlias
from string import Template
Expand Down Expand Up @@ -1531,6 +1531,7 @@ def warning(self, msg, *args, **kwargs):
self._log(WARNING, msg, args, **kwargs)

def warn(self, msg, *args, **kwargs):
import warnings
warnings.warn("The 'warn' method is deprecated, "
"use 'warning' instead", DeprecationWarning, 2)
self.warning(msg, *args, **kwargs)
Expand Down Expand Up @@ -1912,6 +1913,7 @@ def warning(self, msg, *args, **kwargs):
self.log(WARNING, msg, *args, **kwargs)

def warn(self, msg, *args, **kwargs):
import warnings
warnings.warn("The 'warn' method is deprecated, "
"use 'warning' instead", DeprecationWarning, 2)
self.warning(msg, *args, **kwargs)
Expand Down Expand Up @@ -2180,6 +2182,7 @@ def warning(msg, *args, **kwargs):
root.warning(msg, *args, **kwargs)

def warn(msg, *args, **kwargs):
import warnings
warnings.warn("The 'warn' function is deprecated, "
"use 'warning' instead", DeprecationWarning, 2)
warning(msg, *args, **kwargs)
Expand Down Expand Up @@ -2299,6 +2302,7 @@ def _showwarning(message, category, filename, lineno, file=None, line=None):
if _warnings_showwarning is not None:
_warnings_showwarning(message, category, filename, lineno, file, line)
else:
import warnings
s = warnings.formatwarning(message, category, filename, lineno, line)
logger = getLogger("py.warnings")
if not logger.handlers:
Expand All @@ -2316,9 +2320,11 @@ def captureWarnings(capture):
global _warnings_showwarning
if capture:
if _warnings_showwarning is None:
import warnings
_warnings_showwarning = warnings.showwarning
warnings.showwarning = _showwarning
else:
if _warnings_showwarning is not None:
import warnings
warnings.showwarning = _warnings_showwarning
_warnings_showwarning = None
2 changes: 0 additions & 2 deletions Lib/pkgutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
import os
import os.path
import sys
from types import ModuleType
import warnings

__all__ = [
'get_importer', 'iter_importers',
Expand Down
6 changes: 5 additions & 1 deletion Lib/pydoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ class or function within a module or module in a package. If the
import time
import tokenize
import urllib.parse
import warnings
from annotationlib import Format
from collections import deque
from reprlib import Repr
Expand Down Expand Up @@ -376,6 +375,7 @@ def sort_attributes(attrs, object):

def ispackage(path):
"""Guess whether a path refers to a package directory."""
import warnings
warnings.warn('The pydoc.ispackage() function is deprecated',
DeprecationWarning, stacklevel=2)
if os.path.isdir(path):
Expand All @@ -394,6 +394,7 @@ def source_synopsis(file):
if tok_type == tokenize.STRING:
string += tok_string
elif tok_type == tokenize.NEWLINE:
import warnings
with warnings.catch_warnings():
# Ignore the "invalid escape sequence" warning.
warnings.simplefilter("ignore", SyntaxWarning)
Expand Down Expand Up @@ -457,6 +458,7 @@ def __init__(self, filename, exc_info):
self.value = exc_info
self.tb = exc_info.__traceback__
else:
import warnings
warnings.warn("A tuple value for exc_info is deprecated, use an exception instance",
DeprecationWarning)

Expand Down Expand Up @@ -2294,6 +2296,7 @@ def callback(path, modname, desc):
print(modname, desc and '- ' + desc)
def onerror(modname):
pass
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('ignore') # ignore problems during import
ModuleScanner().run(callback, key, onerror=onerror)
Expand Down Expand Up @@ -2543,6 +2546,7 @@ def callback(path, modname, desc):
modname = modname[:-9] + ' (package)'
search_result.append((modname, desc and '- ' + desc))

import warnings
with warnings.catch_warnings():
warnings.filterwarnings('ignore') # ignore problems during import
def onerror(modname):
Expand Down
2 changes: 1 addition & 1 deletion Lib/rlcompleter.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import keyword
import re
import __main__
import warnings

__all__ = ["Completer"]

Expand Down Expand Up @@ -89,6 +88,7 @@ def complete(self, text, state):
return None

if state == 0:
import warnings
with warnings.catch_warnings(action="ignore"):
if "." in text:
self.matches = self.attr_matches(text)
Expand Down
7 changes: 6 additions & 1 deletion Lib/ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,6 @@ class _TLSMessageType:
import socket as _socket
import base64 # for DER-to-PEM translation
import errno
import warnings


socket_error = OSError # keep that public name in module namespace
Expand Down Expand Up @@ -429,6 +428,7 @@ class SSLContext(_SSLContext):

def __new__(cls, protocol=None, *args, **kwargs):
if protocol is None:
import warnings
warnings.warn(
"ssl.SSLContext() without protocol argument is deprecated.",
category=DeprecationWarning,
Expand Down Expand Up @@ -473,6 +473,7 @@ def wrap_bio(self, incoming, outgoing, server_side=False,
)

def set_npn_protocols(self, npn_protocols):
import warnings
warnings.warn(
"ssl NPN is deprecated, use ALPN instead",
DeprecationWarning,
Expand Down Expand Up @@ -521,8 +522,10 @@ def _load_windows_store_certs(self, storename, purpose):
try:
self.load_verify_locations(cadata=cert)
except SSLError as exc:
import warnings
warnings.warn(f"Bad certificate in Windows certificate store: {exc!s}")
except PermissionError:
import warnings
warnings.warn("unable to enumerate Windows certificate store")

def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
Expand Down Expand Up @@ -914,6 +917,7 @@ def selected_npn_protocol(self):
"""Return the currently selected NPN protocol as a string, or ``None``
if a next protocol was not negotiated or if NPN is not supported by one
of the peers."""
import warnings
warnings.warn(
"ssl NPN is deprecated, use ALPN instead",
DeprecationWarning,
Expand Down Expand Up @@ -1183,6 +1187,7 @@ def get_unverified_chain(self):
@_sslcopydoc
def selected_npn_protocol(self):
self._checkClosed()
import warnings
warnings.warn(
"ssl NPN is deprecated, use ALPN instead",
DeprecationWarning,
Expand Down
10 changes: 6 additions & 4 deletions Lib/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
# Imports.

import functools as _functools
import warnings as _warnings
import io as _io
import os as _os
import shutil as _shutil
Expand Down Expand Up @@ -480,7 +479,8 @@ def __del__(self):
close_called = self.close_called
self.cleanup()
if not close_called:
_warnings.warn(self.warn_message, ResourceWarning)
import warnings
warnings.warn(self.warn_message, ResourceWarning)


class _TemporaryFileWrapper:
Expand Down Expand Up @@ -769,7 +769,8 @@ def __iter__(self):

def __del__(self):
if not self.closed:
_warnings.warn(
import warnings
warnings.warn(
"Unclosed file {!r}".format(self),
ResourceWarning,
stacklevel=2,
Expand Down Expand Up @@ -953,7 +954,8 @@ def onexc(func, path, exc):
def _cleanup(cls, name, warn_message, ignore_errors=False, delete=True):
if delete:
cls._rmtree(name, ignore_errors=ignore_errors)
_warnings.warn(warn_message, ResourceWarning)
import warnings
warnings.warn(warn_message, ResourceWarning)

def __repr__(self):
return "<{} {!r}>".format(self.__class__.__name__, self.name)
Expand Down
2 changes: 1 addition & 1 deletion Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import linecache
import sys
import textwrap
import warnings
from contextlib import suppress
import _colorize
from _colorize import ANSIColors
Expand Down Expand Up @@ -1178,6 +1177,7 @@ def from_exception(cls, exc, *args, **kwargs):

@property
def exc_type(self):
import warnings
warnings.warn('Deprecated in 3.13. Use exc_type_str instead.',
DeprecationWarning, stacklevel=2)
return self._exc_type
Expand Down
Loading
Loading