Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3c8a5b4

Browse files
bpo-40275: Avoid importing asyncio in test.support (GH-19600)
* Import asyncio lazily in unittest (only when IsolatedAsyncioTestCase is used). * Import asyncio.events lazily in test.support.
1 parent d4f3923 commit 3c8a5b4

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

Lib/test/support/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
if __name__ != 'test.support':
44
raise ImportError('support must be imported from the test package')
55

6-
import asyncio.events
76
import collections.abc
87
import contextlib
98
import errno
@@ -3260,6 +3259,7 @@ def __gt__(self, other):
32603259

32613260
def maybe_get_event_loop_policy():
32623261
"""Return the global event loop policy if one is set, else return None."""
3262+
import asyncio.events
32633263
return asyncio.events._event_loop_policy
32643264

32653265
# Helpers for testing hashing.

Lib/unittest/__init__.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ def testMultiply(self):
5757
__unittest = True
5858

5959
from .result import TestResult
60-
from .async_case import IsolatedAsyncioTestCase
6160
from .case import (addModuleCleanup, TestCase, FunctionTestCase, SkipTest, skip,
6261
skipIf, skipUnless, expectedFailure)
6362
from .suite import BaseTestSuite, TestSuite
@@ -66,6 +65,7 @@ def testMultiply(self):
6665
from .main import TestProgram, main
6766
from .runner import TextTestRunner, TextTestResult
6867
from .signals import installHandler, registerResult, removeResult, removeHandler
68+
# IsolatedAsyncioTestCase will be imported lazily.
6969

7070
# deprecated
7171
_TextTestResult = TextTestResult
@@ -78,3 +78,18 @@ def load_tests(loader, tests, pattern):
7878
# top level directory cached on loader instance
7979
this_dir = os.path.dirname(__file__)
8080
return loader.discover(start_dir=this_dir, pattern=pattern)
81+
82+
83+
# Lazy import of IsolatedAsyncioTestCase from .async_case
84+
# It imports asyncio, which is relatively heavy, but most tests
85+
# do not need it.
86+
87+
def __dir__():
88+
return globals().keys() | {'IsolatedAsyncioTestCase'}
89+
90+
def __getattr__(name):
91+
if name == 'IsolatedAsyncioTestCase':
92+
global IsolatedAsyncioTestCase
93+
from .async_case import IsolatedAsyncioTestCase
94+
return IsolatedAsyncioTestCase
95+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The :mod:`asyncio` package is now imported lazily in :mod:`unittest` only
2+
when the :class:`~unittest.IsolatedAsyncioTestCase` class is used.

0 commit comments

Comments
 (0)