Skip to content

Commit

Permalink
Defer importing warnings in several modules
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexWaygood committed Oct 3, 2023
1 parent 8c07137 commit 128cc3a
Show file tree
Hide file tree
Showing 11 changed files with 28 additions and 12 deletions.
5 changes: 3 additions & 2 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,6 @@
import re as _re
import sys as _sys

import warnings

from gettext import gettext as _, ngettext

SUPPRESS = '==SUPPRESS=='
Expand Down Expand Up @@ -910,6 +908,7 @@ def __init__(self,
# parser.add_argument('-f', action=BooleanOptionalAction, type=int)
for field_name in ('type', 'choices', 'metavar'):
if locals()[field_name] is not _deprecated_default:
import warnings
warnings._deprecated(
field_name,
"{name!r} is deprecated as of Python 3.12 and will be "
Expand Down Expand Up @@ -1700,6 +1699,7 @@ def _remove_action(self, action):
self._group_actions.remove(action)

def add_argument_group(self, *args, **kwargs):
import warnings
warnings.warn(
"Nesting argument groups is deprecated.",
category=DeprecationWarning,
Expand Down Expand Up @@ -1728,6 +1728,7 @@ def _remove_action(self, action):
self._group_actions.remove(action)

def add_mutually_exclusive_group(self, *args, **kwargs):
import warnings
warnings.warn(
"Nesting mutually exclusive groups is deprecated.",
category=DeprecationWarning,
Expand Down
2 changes: 1 addition & 1 deletion Lib/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from enum import IntEnum, global_enum
import locale as _locale
from itertools import repeat
import warnings

__all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
"firstweekday", "isleap", "leapdays", "weekday", "monthrange",
Expand Down Expand Up @@ -44,6 +43,7 @@ def __str__(self):

def __getattr__(name):
if name in ('January', 'February'):
import warnings
warnings.warn(f"The '{name}' attribute is deprecated, use '{name.upper()}' instead",
DeprecationWarning, stacklevel=2)
if name == 'January':
Expand Down
2 changes: 1 addition & 1 deletion Lib/getpass.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import io
import os
import sys
import warnings

__all__ = ["getpass","getuser","GetPassWarning"]

Expand Down Expand Up @@ -118,6 +117,7 @@ def win_getpass(prompt='Password: ', stream=None):


def fallback_getpass(prompt='Password: ', stream=None):
import warnings
warnings.warn("Can not control echo on the terminal.", GetPassWarning,
stacklevel=2)
if not stream:
Expand Down
3 changes: 2 additions & 1 deletion 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 @@ -84,11 +83,13 @@ def _init_old(self, key, msg, digestmod):
if hasattr(self._inner, 'block_size'):
blocksize = self._inner.block_size
if blocksize < 16:
import warnings as _warnings
_warnings.warn('block_size of %d seems too small; using our '
'default of %d.' % (blocksize, self.blocksize),
RuntimeWarning, 2)
blocksize = self.blocksize
else:
import warnings as _warnings
_warnings.warn('No block_size attribute on given digest object; '
'Assuming %d.' % (self.blocksize),
RuntimeWarning, 2)
Expand Down
5 changes: 4 additions & 1 deletion Lib/mailbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import socket
import errno
import copy
import warnings
import email
import email.message
import email.generator
Expand Down Expand Up @@ -223,6 +222,7 @@ def _dump_message(self, message, target, mangle_from_=False):
target.write(linesep)
elif isinstance(message, (str, bytes, io.StringIO)):
if isinstance(message, io.StringIO):
import warnings
warnings.warn("Use of StringIO input is deprecated, "
"use BytesIO instead", DeprecationWarning, 3)
message = message.getvalue()
Expand All @@ -237,6 +237,7 @@ def _dump_message(self, message, target, mangle_from_=False):
target.write(linesep)
elif hasattr(message, 'read'):
if hasattr(message, 'buffer'):
import warnings
warnings.warn("Use of text mode files is deprecated, "
"use a binary mode file instead", DeprecationWarning, 3)
message = message.buffer
Expand Down Expand Up @@ -1432,6 +1433,7 @@ def _install_message(self, message):
self._file.write(buffer.replace(b'\n', linesep))
elif isinstance(message, (bytes, str, io.StringIO)):
if isinstance(message, io.StringIO):
import warnings
warnings.warn("Use of StringIO input is deprecated, "
"use BytesIO instead", DeprecationWarning, 3)
message = message.getvalue()
Expand All @@ -1448,6 +1450,7 @@ def _install_message(self, message):
self._file.write(message.replace(b'\n', linesep))
elif hasattr(message, 'readline'):
if hasattr(message, 'buffer'):
import warnings
warnings.warn("Use of text mode files is deprecated, "
"use a binary mode file instead", DeprecationWarning, 3)
message = message.buffer
Expand Down
5 changes: 4 additions & 1 deletion Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import posixpath
import re
import sys
import warnings
from _collections_abc import Sequence
from errno import ENOENT, ENOTDIR, EBADF, ELOOP, EINVAL
from stat import S_ISDIR, S_ISLNK, S_ISREG, S_ISSOCK, S_ISBLK, S_ISCHR, S_ISFIFO
Expand Down Expand Up @@ -643,6 +642,7 @@ def relative_to(self, other, /, *_deprecated, walk_up=False):
the path.
"""
if _deprecated:
import warnings
msg = ("support for supplying more than one positional argument "
"to pathlib.PurePath.relative_to() is deprecated and "
"scheduled for removal in Python {remove}")
Expand All @@ -665,6 +665,7 @@ def is_relative_to(self, other, /, *_deprecated):
"""Return True if the path is relative to another path or False.
"""
if _deprecated:
import warnings
msg = ("support for supplying more than one argument to "
"pathlib.PurePath.is_relative_to() is deprecated and "
"scheduled for removal in Python {remove}")
Expand Down Expand Up @@ -1115,6 +1116,7 @@ def _glob(self, pattern, case_sensitive, follow_symlinks):
# GH-65238: pathlib doesn't preserve trailing slash. Add it back.
pattern_parts.append('')
if pattern_parts[-1] == '**':
import warnings
# GH-70303: '**' only matches directories. Add trailing slash.
warnings.warn(
"Pattern ending '**' will match files and directories in a "
Expand Down Expand Up @@ -1445,6 +1447,7 @@ class Path(_PathBase):

def __init__(self, *args, **kwargs):
if kwargs:
import warnings
msg = ("support for supplying keyword arguments to pathlib.PurePath "
"is deprecated and scheduled for removal in Python {remove}")
warnings._deprecated("pathlib.PurePath(**kwargs)", msg, remove=(3, 14))
Expand Down
3 changes: 2 additions & 1 deletion Lib/pkgutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import os.path
import sys
from types import ModuleType
import warnings

__all__ = [
'get_importer', 'iter_importers', 'get_loader', 'find_loader',
Expand Down Expand Up @@ -270,6 +269,7 @@ def get_loader(module_or_name):
If the named module is not already imported, its containing package
(if any) is imported, in order to establish the package __path__.
"""
import warnings
warnings._deprecated("pkgutil.get_loader",
f"{warnings._DEPRECATED_MSG}; "
"use importlib.util.find_spec() instead",
Expand Down Expand Up @@ -298,6 +298,7 @@ def find_loader(fullname):
importlib.util.find_spec that converts most failures to ImportError
and only returns the loader rather than the full spec
"""
import warnings
warnings._deprecated("pkgutil.find_loader",
f"{warnings._DEPRECATED_MSG}; "
"use importlib.util.find_spec() instead",
Expand Down
2 changes: 1 addition & 1 deletion Lib/shutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import fnmatch
import collections
import errno
import warnings

try:
import zlib
Expand Down Expand Up @@ -723,6 +722,7 @@ def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None):
"""

if onerror is not None:
import warnings
warnings.warn("onerror argument is deprecated, use onexc instead",
DeprecationWarning, stacklevel=2)

Expand Down
2 changes: 1 addition & 1 deletion Lib/tarfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@
import struct
import copy
import re
import warnings

try:
import pwd
Expand Down Expand Up @@ -2219,6 +2218,7 @@ def _get_filter_function(self, filter):
if filter is None:
filter = self.extraction_filter
if filter is None:
import warnings
warnings.warn(
'Python 3.14 will, by default, filter extracted tar '
+ 'archives and reject files or modify their metadata. '
Expand Down
4 changes: 3 additions & 1 deletion Lib/wsgiref/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@

import re
import sys
import warnings

header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
bad_header_value_re = re.compile(r'[\000-\037]')
Expand Down Expand Up @@ -310,6 +309,7 @@ def check_environ(environ):
"(use %s instead)" % (key, key[5:]))

if 'QUERY_STRING' not in environ:
import warnings
warnings.warn(
'QUERY_STRING is not in the WSGI environment; the cgi '
'module will use sys.argv when this variable is missing, '
Expand All @@ -335,6 +335,7 @@ def check_environ(environ):
# @@: these need filling out:
if environ['REQUEST_METHOD'] not in (
'GET', 'HEAD', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE', 'TRACE'):
import warnings
warnings.warn(
"Unknown REQUEST_METHOD: %r" % environ['REQUEST_METHOD'],
WSGIWarning)
Expand Down Expand Up @@ -378,6 +379,7 @@ def check_status(status):
status_int = int(status_code)
assert_(status_int >= 100, "Status code is invalid: %r" % status_int)
if len(status) < 4 or status[3] != ' ':
import warnings
warnings.warn(
"The status string (%r) should be a three-digit integer "
"followed by a single space and a status explanation"
Expand Down
7 changes: 6 additions & 1 deletion Lib/xml/etree/ElementTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,6 @@

import sys
import re
import warnings
import io
import collections
import collections.abc
Expand Down Expand Up @@ -199,6 +198,7 @@ def __len__(self):
return len(self._children)

def __bool__(self):
import warnings
warnings.warn(
"Testing an element's truth value will raise an exception in "
"future versions. "
Expand Down Expand Up @@ -601,6 +601,7 @@ def find(self, path, namespaces=None):
# assert self._root is not None
if path[:1] == "/":
path = "." + path
import warnings
warnings.warn(
"This search is broken in 1.3 and earlier, and will be "
"fixed in a future version. If you rely on the current "
Expand All @@ -623,6 +624,7 @@ def findtext(self, path, default=None, namespaces=None):
# assert self._root is not None
if path[:1] == "/":
path = "." + path
import warnings
warnings.warn(
"This search is broken in 1.3 and earlier, and will be "
"fixed in a future version. If you rely on the current "
Expand All @@ -645,6 +647,7 @@ def findall(self, path, namespaces=None):
# assert self._root is not None
if path[:1] == "/":
path = "." + path
import warnings
warnings.warn(
"This search is broken in 1.3 and earlier, and will be "
"fixed in a future version. If you rely on the current "
Expand All @@ -667,6 +670,7 @@ def iterfind(self, path, namespaces=None):
# assert self._root is not None
if path[:1] == "/":
path = "." + path
import warnings
warnings.warn(
"This search is broken in 1.3 and earlier, and will be "
"fixed in a future version. If you rely on the current "
Expand Down Expand Up @@ -1681,6 +1685,7 @@ def _default(self, text):
if hasattr(self.target, "doctype"):
self.target.doctype(name, pubid, system[1:-1])
elif hasattr(self, "doctype"):
import warnings
warnings.warn(
"The doctype() method of XMLParser is ignored. "
"Define doctype() method on the TreeBuilder target.",
Expand Down

0 comments on commit 128cc3a

Please sign in to comment.