Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 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
17 changes: 12 additions & 5 deletions 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 @@ -47,15 +46,18 @@
PyCF_ONLY_AST = 0x400
PyCF_ALLOW_INCOMPLETE_INPUT = 0x4000


def _maybe_compile(compiler, source, filename, symbol):
# Check for source consisting of only blank lines and comments.
for line in source.split("\n"):
line = line.strip()
if line and line[0] != '#':
break # Leave it alone.
if line and line[0] != "#":
break # Leave it alone.
else:
if symbol != "eval":
source = "pass" # Replace it with a 'pass' statement
source = "pass" # Replace it with a 'pass' statement

import warnings

# Disable compiler warnings when checking for incomplete input.
with warnings.catch_warnings():
Expand All @@ -74,13 +76,15 @@ def _maybe_compile(compiler, source, filename, symbol):

return compiler(source, filename, symbol, incomplete_input=False)


def _compile(source, filename, symbol, incomplete_input=True):
flags = 0
if incomplete_input:
flags |= PyCF_ALLOW_INCOMPLETE_INPUT
flags |= PyCF_DONT_IMPLY_DEDENT
return compile(source, filename, symbol, flags)


def compile_command(source, filename="<input>", symbol="single"):
r"""Compile a command and determine whether it is incomplete.

Expand All @@ -102,17 +106,19 @@ def compile_command(source, filename="<input>", symbol="single"):
"""
return _maybe_compile(_compile, source, filename, symbol)


class Compile:
"""Instances of this class behave much like the built-in compile
function, but if one is used to compile text containing a future
statement, it "remembers" and compiles all subsequent program texts
with the statement in force."""

def __init__(self):
self.flags = PyCF_DONT_IMPLY_DEDENT | PyCF_ALLOW_INCOMPLETE_INPUT

def __call__(self, source, filename, symbol, flags=0, **kwargs):
flags |= self.flags
if kwargs.get('incomplete_input', True) is False:
if kwargs.get("incomplete_input", True) is False:
flags &= ~PyCF_DONT_IMPLY_DEDENT
flags &= ~PyCF_ALLOW_INCOMPLETE_INPUT
codeob = compile(source, filename, symbol, flags, True)
Expand All @@ -123,6 +129,7 @@ def __call__(self, source, filename, symbol, flags=0, **kwargs):
self.flags |= feature.compiler_flag
return codeob


class CommandCompiler:
"""Instances of this class have __call__ methods identical in
signature to compile_command; the difference is that if the
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: 5 additions & 6 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 @@ -31,9 +30,7 @@ class HMAC:
"""
blocksize = 64 # 512-bit HMAC; can be changed in subclasses.

__slots__ = (
"_hmac", "_inner", "_outer", "block_size", "digest_size"
)
__slots__ = ("_hmac", "_inner", "_outer", "block_size", "digest_size")

def __init__(self, key, msg=None, digestmod=''):
"""Create a new HMAC object.
Expand Down Expand Up @@ -81,15 +78,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 '
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
6 changes: 5 additions & 1 deletion Lib/importlib/_bootstrap_external.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import _imp
import _io
import sys
import _warnings
import marshal


Expand Down Expand Up @@ -259,6 +258,7 @@ def cache_from_source(path, debug_override=None, *, optimization=None):

"""
if debug_override is not None:
import _warnings
_warnings.warn('the debug_override parameter is deprecated; use '
"'optimization' instead", DeprecationWarning)
if optimization is not None:
Expand Down Expand Up @@ -663,13 +663,15 @@ def _bless_my_loader(module_globals):
if loader is None:
exc = AttributeError if spec_loader is missing else ValueError
raise exc('Module globals is missing a __spec__.loader')
import _warnings
_warnings.warn(
'Module globals is missing a __spec__.loader',
DeprecationWarning)
spec_loader = loader

assert spec_loader is not None
if loader is not None and loader != spec_loader:
import _warnings
_warnings.warn(
'Module globals; __loader__ != __spec__.loader',
DeprecationWarning)
Expand Down Expand Up @@ -716,6 +718,7 @@ def _search_registry(cls, fullname):

@classmethod
def find_spec(cls, fullname, path=None, target=None):
import _warnings
_warnings.warn('importlib.machinery.WindowsRegistryFinder is '
'deprecated; use site configuration instead. '
'Future versions of Python may not enable this '
Expand Down Expand Up @@ -1224,6 +1227,7 @@ def invalidate_caches():
def _path_hooks(path):
"""Search sys.path_hooks for a finder for 'path'."""
if sys.path_hooks is not None and not sys.path_hooks:
import _warnings
_warnings.warn('sys.path_hooks is empty', ImportWarning)
for hook in sys.path_hooks:
try:
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
5 changes: 3 additions & 2 deletions Lib/rlcompleter.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@
import keyword
import re
import __main__
import warnings

__all__ = ["Completer"]


class Completer:
def __init__(self, namespace = None):
def __init__(self, namespace=None):
"""Create a new completer for the command line.

Completer([namespace]) -> completer instance.
Expand Down Expand Up @@ -89,6 +89,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
Loading
Loading