Skip to content

Commit 280757b

Browse files
committed
gh-142349: Move all lazy-imports-by-hand to use the new lazy keyword
1 parent 837166f commit 280757b

File tree

205 files changed

+694
-579
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

205 files changed

+694
-579
lines changed

Lib/_aix_support.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
"""Shared AIX support functions."""
22

3+
lazy import os
4+
lazy import contextlib
5+
36
import sys
47
import sysconfig
58

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

Lib/_collections_abc.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@
3232
#
3333
#######################################################################
3434

35+
lazy from annotationlib import type_repr
36+
lazy import warnings
37+
3538
from abc import ABCMeta, abstractmethod
3639
import sys
3740

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

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

10751076
def __instancecheck__(cls, instance):
1076-
import warnings
10771077

10781078
warnings._deprecated(
10791079
"collections.abc.ByteString",
@@ -1170,7 +1170,6 @@ def __iadd__(self, values):
11701170

11711171
def __getattr__(attr):
11721172
if attr == "ByteString":
1173-
import warnings
11741173
warnings._deprecated("collections.abc.ByteString", remove=(3, 17))
11751174
globals()["ByteString"] = _deprecated_ByteString
11761175
return _deprecated_ByteString

Lib/_osx_support.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Shared OS X support functions."""
22

3+
lazy import contextlib
4+
35
import os
46
import re
57
import sys
@@ -58,7 +60,6 @@ def _read_output(commandstring, capture_stderr=False):
5860
# but without actually using os.popen because that
5961
# function is not usable during python bootstrap.
6062
# tempfile is also not available then.
61-
import contextlib
6263
try:
6364
import tempfile
6465
fp = tempfile.NamedTemporaryFile()

Lib/_pydatetime.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
"""Pure Python implementation of the datetime module."""
22

3+
lazy import _strptime
4+
lazy import warnings
5+
36
__all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo",
47
"MINYEAR", "MAXYEAR", "UTC")
58

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

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

14751476
# Read-only field accessors
@@ -1908,7 +1909,6 @@ def fromtimestamp(cls, timestamp, tz=None):
19081909
@classmethod
19091910
def utcfromtimestamp(cls, t):
19101911
"""Construct a naive UTC datetime from a POSIX timestamp."""
1911-
import warnings
19121912
warnings.warn("datetime.datetime.utcfromtimestamp() is deprecated and scheduled "
19131913
"for removal in a future version. Use timezone-aware "
19141914
"objects to represent datetimes in UTC: "
@@ -1926,7 +1926,6 @@ def now(cls, tz=None):
19261926
@classmethod
19271927
def utcnow(cls):
19281928
"Construct a UTC datetime from time.time()."
1929-
import warnings
19301929
warnings.warn("datetime.datetime.utcnow() is deprecated and scheduled for "
19311930
"removal in a future version. Use timezone-aware "
19321931
"objects to represent datetimes in UTC: "
@@ -2217,7 +2216,6 @@ def strptime(cls, date_string, format):
22172216
For a list of supported format codes, see the documentation:
22182217
https://docs.python.org/3/library/datetime.html#format-codes
22192218
"""
2220-
import _strptime
22212219
return _strptime._strptime_datetime_datetime(cls, date_string, format)
22222220

22232221
def utcoffset(self):

Lib/_pydecimal.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515

1616
"""Python decimal arithmetic module"""
1717

18+
lazy from itertools import chain as _chain, repeat as _repeat
19+
lazy from warnings import _deprecated as _warnings_deprecated
20+
1821
__all__ = [
1922
# Two major classes
2023
'Decimal', 'Context',
@@ -6279,11 +6282,10 @@ def _group_lengths(grouping):
62796282
# (2) nonempty list of positive integers + [0]
62806283
# (3) list of positive integers + [locale.CHAR_MAX], or
62816284

6282-
from itertools import chain, repeat
62836285
if not grouping:
62846286
return []
62856287
elif grouping[-1] == 0 and len(grouping) >= 2:
6286-
return chain(grouping[:-1], repeat(grouping[-2]))
6288+
return _chain(grouping[:-1], _repeat(grouping[-2]))
62876289
elif grouping[-1] == _locale.CHAR_MAX:
62886290
return grouping[:-1]
62896291
else:
@@ -6405,8 +6407,7 @@ def _format_number(is_negative, intpart, fracpart, exp, spec):
64056407

64066408
def __getattr__(name):
64076409
if name == "__version__":
6408-
from warnings import _deprecated
64096410

6410-
_deprecated("__version__", remove=(3, 20))
6411+
_warnings_deprecated("__version__", remove=(3, 20))
64116412
return SPEC_VERSION
64126413
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

Lib/_pyio.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
Python implementation of the io module.
33
"""
44

5+
lazy import warnings
6+
57
import os
68
import abc
79
import codecs
@@ -59,7 +61,6 @@ def text_encoding(encoding, stacklevel=2):
5961
else:
6062
encoding = "locale"
6163
if sys.flags.warn_default_encoding:
62-
import warnings
6364
warnings.warn("'encoding' argument not specified.",
6465
EncodingWarning, stacklevel + 1)
6566
return encoding
@@ -225,7 +226,6 @@ def open(file, mode="r", buffering=-1, encoding=None, errors=None,
225226
if binary and newline is not None:
226227
raise ValueError("binary mode doesn't take a newline argument")
227228
if binary and buffering == 1:
228-
import warnings
229229
warnings.warn("line buffering (buffering=1) isn't supported in binary "
230230
"mode, the default buffer size will be used",
231231
RuntimeWarning, 2)
@@ -283,7 +283,6 @@ def _open_code_with_warning(path):
283283
in order to allow embedders more control over code files.
284284
This functionality is not supported on the current runtime.
285285
"""
286-
import warnings
287286
warnings.warn("_pyio.open_code() may not be using hooks",
288287
RuntimeWarning, 2)
289288
return open(path, "rb")
@@ -1530,7 +1529,6 @@ def __init__(self, file, mode='r', closefd=True, opener=None):
15301529
raise TypeError('integer argument expected, got float')
15311530
if isinstance(file, int):
15321531
if isinstance(file, bool):
1533-
import warnings
15341532
warnings.warn("bool is used as a file descriptor",
15351533
RuntimeWarning, stacklevel=2)
15361534
file = int(file)
@@ -1633,7 +1631,6 @@ def __init__(self, file, mode='r', closefd=True, opener=None):
16331631

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

Lib/_pylong.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
tricky or non-obvious code is not worth it. For people looking for
1313
maximum performance, they should use something like gmpy2."""
1414

15+
lazy from decimal import Decimal as D
16+
1517
import re
1618
import decimal
1719
try:
@@ -149,7 +151,6 @@ def int_to_decimal(n):
149151
# "clever" recursive way. If we want a string representation, we
150152
# apply str to _that_.
151153

152-
from decimal import Decimal as D
153154
BITLIM = 200
154155

155156
# Don't bother caching the "lo" mask in this; the time to compute it is

Lib/_pyrepl/_threading_handler.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from __future__ import annotations
22

3+
lazy import threading
4+
35
from dataclasses import dataclass, field
46
import traceback
57

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

2931

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

3334
@dataclass
3435
class ExceptHookHandler:

Lib/_pyrepl/commands.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@
2020
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2121

2222
from __future__ import annotations
23+
lazy import signal
24+
lazy import _sitebuiltins
25+
lazy from .pager import get_pager
26+
lazy from site import gethistoryfile
27+
2328
import os
2429
import time
2530

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

216221
class interrupt(FinishCommand):
217222
def do(self) -> None:
218-
import signal
219223

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

232236
class suspend(Command):
233237
def do(self) -> None:
234-
import signal
235238

236239
r = self.reader
237240
p = r.pos
@@ -446,7 +449,6 @@ def do(self) -> None:
446449

447450
class help(Command):
448451
def do(self) -> None:
449-
import _sitebuiltins
450452

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

468470
class show_history(Command):
469471
def do(self) -> None:
470-
from .pager import get_pager
471-
from site import gethistoryfile
472472

473473
history = os.linesep.join(self.reader.history[:])
474474
self.reader.console.restore()

Lib/_pyrepl/console.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919

2020
from __future__ import annotations
2121

22+
lazy import traceback
23+
2224
import _colorize
2325

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

172174
def _excepthook(self, typ, value, tb):
173-
import traceback
174175
lines = traceback.format_exception(
175176
typ, value, tb,
176177
colorize=self.can_colorize,

0 commit comments

Comments
 (0)