Skip to content
Draft
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
5 changes: 3 additions & 2 deletions Lib/_aix_support.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
"""Shared AIX support functions."""

lazy import os
lazy import contextlib

import sys
import sysconfig

Expand All @@ -10,8 +13,6 @@ def _read_cmd_output(commandstring, capture_stderr=False):
# Similar to os.popen(commandstring, "r").read(),
# but without actually using os.popen because that
# function is not usable during python bootstrap.
import os
import contextlib
fp = open("/tmp/_aix_support.%s"%(
os.getpid(),), "w+b")

Expand Down
7 changes: 3 additions & 4 deletions Lib/_collections_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
#
#######################################################################

lazy from annotationlib import type_repr
lazy import warnings

from abc import ABCMeta, abstractmethod
import sys

Expand Down Expand Up @@ -485,7 +488,6 @@ def __new__(cls, origin, args):
def __repr__(self):
if len(self.__args__) == 2 and _is_param_expr(self.__args__[0]):
return super().__repr__()
from annotationlib import type_repr
return (f'collections.abc.Callable'
f'[[{", ".join([type_repr(a) for a in self.__args__[:-1]])}], '
f'{type_repr(self.__args__[-1])}]')
Expand Down Expand Up @@ -1064,7 +1066,6 @@ def count(self, value):
class _DeprecateByteStringMeta(ABCMeta):
def __new__(cls, name, bases, namespace, **kwargs):
if name != "ByteString":
import warnings

warnings._deprecated(
"collections.abc.ByteString",
Expand All @@ -1073,7 +1074,6 @@ def __new__(cls, name, bases, namespace, **kwargs):
return super().__new__(cls, name, bases, namespace, **kwargs)

def __instancecheck__(cls, instance):
import warnings

warnings._deprecated(
"collections.abc.ByteString",
Expand Down Expand Up @@ -1170,7 +1170,6 @@ def __iadd__(self, values):

def __getattr__(attr):
if attr == "ByteString":
import warnings
warnings._deprecated("collections.abc.ByteString", remove=(3, 17))
globals()["ByteString"] = _deprecated_ByteString
return _deprecated_ByteString
Expand Down
3 changes: 2 additions & 1 deletion Lib/_osx_support.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Shared OS X support functions."""

lazy import contextlib

import os
import re
import sys
Expand Down Expand Up @@ -58,7 +60,6 @@ def _read_output(commandstring, capture_stderr=False):
# but without actually using os.popen because that
# function is not usable during python bootstrap.
# tempfile is also not available then.
import contextlib
try:
import tempfile
fp = tempfile.NamedTemporaryFile()
Expand Down
8 changes: 3 additions & 5 deletions Lib/_pydatetime.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
"""Pure Python implementation of the datetime module."""

lazy import _strptime
lazy import warnings

__all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo",
"MINYEAR", "MAXYEAR", "UTC")

Expand Down Expand Up @@ -1077,7 +1080,6 @@ def strptime(cls, date_string, format):
For a list of supported format codes, see the documentation:
https://docs.python.org/3/library/datetime.html#format-codes
"""
import _strptime
return _strptime._strptime_datetime_date(cls, date_string, format)

# Conversions to string
Expand Down Expand Up @@ -1469,7 +1471,6 @@ def strptime(cls, date_string, format):
For a list of supported format codes, see the documentation:
https://docs.python.org/3/library/datetime.html#format-codes
"""
import _strptime
return _strptime._strptime_datetime_time(cls, date_string, format)

# Read-only field accessors
Expand Down Expand Up @@ -1908,7 +1909,6 @@ def fromtimestamp(cls, timestamp, tz=None):
@classmethod
def utcfromtimestamp(cls, t):
"""Construct a naive UTC datetime from a POSIX timestamp."""
import warnings
warnings.warn("datetime.datetime.utcfromtimestamp() is deprecated and scheduled "
"for removal in a future version. Use timezone-aware "
"objects to represent datetimes in UTC: "
Expand All @@ -1926,7 +1926,6 @@ def now(cls, tz=None):
@classmethod
def utcnow(cls):
"Construct a UTC datetime from time.time()."
import warnings
warnings.warn("datetime.datetime.utcnow() is deprecated and scheduled for "
"removal in a future version. Use timezone-aware "
"objects to represent datetimes in UTC: "
Expand Down Expand Up @@ -2217,7 +2216,6 @@ def strptime(cls, date_string, format):
For a list of supported format codes, see the documentation:
https://docs.python.org/3/library/datetime.html#format-codes
"""
import _strptime
return _strptime._strptime_datetime_datetime(cls, date_string, format)

def utcoffset(self):
Expand Down
9 changes: 5 additions & 4 deletions Lib/_pydecimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@

"""Python decimal arithmetic module"""

lazy from itertools import chain as _chain, repeat as _repeat
lazy from warnings import _deprecated as _warnings_deprecated

__all__ = [
# Two major classes
'Decimal', 'Context',
Expand Down Expand Up @@ -6279,11 +6282,10 @@ def _group_lengths(grouping):
# (2) nonempty list of positive integers + [0]
# (3) list of positive integers + [locale.CHAR_MAX], or

from itertools import chain, repeat
if not grouping:
return []
elif grouping[-1] == 0 and len(grouping) >= 2:
return chain(grouping[:-1], repeat(grouping[-2]))
return _chain(grouping[:-1], _repeat(grouping[-2]))
elif grouping[-1] == _locale.CHAR_MAX:
return grouping[:-1]
else:
Expand Down Expand Up @@ -6405,8 +6407,7 @@ def _format_number(is_negative, intpart, fracpart, exp, spec):

def __getattr__(name):
if name == "__version__":
from warnings import _deprecated

_deprecated("__version__", remove=(3, 20))
_warnings_deprecated("__version__", remove=(3, 20))
return SPEC_VERSION
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
7 changes: 2 additions & 5 deletions Lib/_pyio.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Python implementation of the io module.
"""

lazy import warnings

import os
import abc
import codecs
Expand Down Expand Up @@ -59,7 +61,6 @@ def text_encoding(encoding, stacklevel=2):
else:
encoding = "locale"
if sys.flags.warn_default_encoding:
import warnings
warnings.warn("'encoding' argument not specified.",
EncodingWarning, stacklevel + 1)
return encoding
Expand Down Expand Up @@ -225,7 +226,6 @@ def open(file, mode="r", buffering=-1, encoding=None, errors=None,
if binary and newline is not None:
raise ValueError("binary mode doesn't take a newline argument")
if binary and buffering == 1:
import warnings
warnings.warn("line buffering (buffering=1) isn't supported in binary "
"mode, the default buffer size will be used",
RuntimeWarning, 2)
Expand Down Expand Up @@ -283,7 +283,6 @@ def _open_code_with_warning(path):
in order to allow embedders more control over code files.
This functionality is not supported on the current runtime.
"""
import warnings
warnings.warn("_pyio.open_code() may not be using hooks",
RuntimeWarning, 2)
return open(path, "rb")
Expand Down Expand Up @@ -1530,7 +1529,6 @@ def __init__(self, file, mode='r', closefd=True, opener=None):
raise TypeError('integer argument expected, got float')
if isinstance(file, int):
if isinstance(file, bool):
import warnings
warnings.warn("bool is used as a file descriptor",
RuntimeWarning, stacklevel=2)
file = int(file)
Expand Down Expand Up @@ -1633,7 +1631,6 @@ def __init__(self, file, mode='r', closefd=True, opener=None):

def _dealloc_warn(self, source):
if self._fd >= 0 and self._closefd and not self.closed:
import warnings
warnings.warn(f'unclosed file {source!r}', ResourceWarning,
stacklevel=2, source=self)

Expand Down
3 changes: 2 additions & 1 deletion Lib/_pylong.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
tricky or non-obvious code is not worth it. For people looking for
maximum performance, they should use something like gmpy2."""

lazy from decimal import Decimal as D

import re
import decimal
try:
Expand Down Expand Up @@ -149,7 +151,6 @@ def int_to_decimal(n):
# "clever" recursive way. If we want a string representation, we
# apply str to _that_.

from decimal import Decimal as D
BITLIM = 200

# Don't bother caching the "lo" mask in this; the time to compute it is
Expand Down
3 changes: 2 additions & 1 deletion Lib/_pyrepl/_threading_handler.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

lazy import threading

from dataclasses import dataclass, field
import traceback

Expand Down Expand Up @@ -28,7 +30,6 @@ def add(self, s: str) -> None: ...


def install_threading_hook(reader: Reader) -> None:
import threading

@dataclass
class ExceptHookHandler:
Expand Down
10 changes: 5 additions & 5 deletions Lib/_pyrepl/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

from __future__ import annotations
lazy import signal
lazy import _sitebuiltins
lazy from .pager import get_pager
lazy from site import gethistoryfile

import os
import time

Expand Down Expand Up @@ -215,7 +220,6 @@ def do(self) -> None:

class interrupt(FinishCommand):
def do(self) -> None:
import signal

self.reader.console.finish()
self.reader.finish()
Expand All @@ -231,7 +235,6 @@ def do(self) -> None:

class suspend(Command):
def do(self) -> None:
import signal

r = self.reader
p = r.pos
Expand Down Expand Up @@ -446,7 +449,6 @@ def do(self) -> None:

class help(Command):
def do(self) -> None:
import _sitebuiltins

with self.reader.suspend():
self.reader.msg = _sitebuiltins._Helper()() # type: ignore[assignment]
Expand All @@ -467,8 +469,6 @@ def do(self) -> None:

class show_history(Command):
def do(self) -> None:
from .pager import get_pager
from site import gethistoryfile

history = os.linesep.join(self.reader.history[:])
self.reader.console.restore()
Expand Down
3 changes: 2 additions & 1 deletion Lib/_pyrepl/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

from __future__ import annotations

lazy import traceback

import _colorize

from abc import ABC, abstractmethod
Expand Down Expand Up @@ -170,7 +172,6 @@ def showsyntaxerror(self, filename=None, **kwargs):
super().showsyntaxerror(filename=filename, **kwargs)

def _excepthook(self, typ, value, tb):
import traceback
lines = traceback.format_exception(
typ, value, tb,
colorize=self.can_colorize,
Expand Down
3 changes: 2 additions & 1 deletion Lib/_pyrepl/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@

from __future__ import annotations

lazy from .keymap import compile_keymap, parse_keys

from abc import ABC, abstractmethod
import unicodedata
from collections import deque
Expand Down Expand Up @@ -62,7 +64,6 @@ def empty(self) -> bool:
class KeymapTranslator(InputTranslator):
def __init__(self, keymap, verbose=False, invalid_cls=None, character_cls=None):
self.verbose = verbose
from .keymap import compile_keymap, parse_keys

self.keymap = keymap
self.invalid_cls = invalid_cls
Expand Down
9 changes: 5 additions & 4 deletions Lib/_pyrepl/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
lazy from .trace import trace
lazy import tokenize
lazy from .console import InteractiveColoredConsole
lazy from .simple_interact import run_multiline_interactive_console

import errno
import os
import sys
Expand Down Expand Up @@ -25,7 +30,6 @@
def interactive_console(mainmodule=None, quiet=False, pythonstartup=False):
if not CAN_USE_PYREPL:
if not os.getenv('PYTHON_BASIC_REPL') and FAIL_REASON:
from .trace import trace
trace(FAIL_REASON)
print(FAIL_REASON, file=sys.stderr)
return sys._baserepl()
Expand All @@ -40,7 +44,6 @@ def interactive_console(mainmodule=None, quiet=False, pythonstartup=False):
if pythonstartup and startup_path:
sys.audit("cpython.run_startup", startup_path)

import tokenize
with tokenize.open(startup_path) as f:
startup_code = compile(f.read(), startup_path, "exec")
exec(startup_code, namespace)
Expand All @@ -52,7 +55,5 @@ def interactive_console(mainmodule=None, quiet=False, pythonstartup=False):
if not hasattr(sys, "ps2"):
sys.ps2 = "... "

from .console import InteractiveColoredConsole
from .simple_interact import run_multiline_interactive_console
console = InteractiveColoredConsole(namespace, filename="<stdin>")
run_multiline_interactive_console(console)
6 changes: 3 additions & 3 deletions Lib/_pyrepl/pager.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from __future__ import annotations

lazy import tempfile
lazy import subprocess

import io
import os
import re
Expand Down Expand Up @@ -41,7 +44,6 @@ def get_pager() -> Pager:
if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
return lambda text, title='': pipe_pager(text, 'less', title)

import tempfile
(fd, filename) = tempfile.mkstemp()
os.close(fd)
try:
Expand Down Expand Up @@ -126,7 +128,6 @@ def plain_pager(text: str, title: str = '') -> None:

def pipe_pager(text: str, cmd: str, title: str = '') -> None:
"""Page through text by feeding it to another program."""
import subprocess
env = os.environ.copy()
if title:
title += ' '
Expand Down Expand Up @@ -164,7 +165,6 @@ def pipe_pager(text: str, cmd: str, title: str = '') -> None:

def tempfile_pager(text: str, cmd: str, title: str = '') -> None:
"""Page through text by invoking a program on a temporary file."""
import tempfile
with tempfile.TemporaryDirectory() as tempdir:
filename = os.path.join(tempdir, 'pydoc.out')
with open(filename, 'w', errors='backslashreplace',
Expand Down
Loading
Loading