Skip to content

Commit a438592

Browse files
authored
Defer creation of ready future (#858)
1 parent 30cbf97 commit a438592

File tree

2 files changed

+17
-15
lines changed

2 files changed

+17
-15
lines changed

jupyter_client/manager.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,16 @@ class _ShutdownStatus(Enum):
5454
F = t.TypeVar('F', bound=t.Callable[..., t.Any])
5555

5656

57+
def _get_future() -> t.Union[Future, CFuture]:
58+
"""Get an appropriate Future object"""
59+
try:
60+
asyncio.get_running_loop()
61+
return Future()
62+
except RuntimeError:
63+
# No event loop running, use concurrent future
64+
return CFuture()
65+
66+
5767
def in_pending_state(method: F) -> F:
5868
"""Sets the kernel to a pending state by
5969
creating a fresh Future for the KernelManager's `ready`
@@ -64,12 +74,8 @@ def in_pending_state(method: F) -> F:
6474
@functools.wraps(method)
6575
async def wrapper(self, *args, **kwargs):
6676
# Create a future for the decorated method
67-
if self._attempted_start:
68-
try:
69-
self._ready = Future()
70-
except RuntimeError:
71-
# No event loop running, use concurrent future
72-
self._ready = CFuture()
77+
if self._attempted_start or not self._ready:
78+
self._ready = _get_future()
7379
try:
7480
# call wrapped method, await, and set the result or exception.
7581
out = await method(self, *args, **kwargs)
@@ -91,19 +97,13 @@ class KernelManager(ConnectionFileMixin):
9197
This version starts kernels with Popen.
9298
"""
9399

94-
_ready: t.Union[Future, CFuture]
100+
_ready: t.Optional[t.Union[Future, CFuture]]
95101

96102
def __init__(self, *args, **kwargs):
97103
super().__init__(**kwargs)
98104
self._shutdown_status = _ShutdownStatus.Unset
99105
self._attempted_start = False
100-
# Create a place holder future.
101-
try:
102-
asyncio.get_running_loop()
103-
self._ready = Future()
104-
except RuntimeError:
105-
# No event loop running, use concurrent future
106-
self._ready = CFuture()
106+
self._ready = None
107107

108108
_created_context: Bool = Bool(False)
109109

@@ -188,6 +188,8 @@ def _default_cache_ports(self) -> bool:
188188
@property
189189
def ready(self) -> t.Union[CFuture, Future]:
190190
"""A future that resolves when the kernel process has started for the first time"""
191+
if not self._ready:
192+
self._ready = _get_future()
191193
return self._ready
192194

193195
@property

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ Homepage = "https://jupyter.org"
5050
test = [
5151
"codecov",
5252
"coverage",
53-
"ipykernel>=6.5",
53+
"ipykernel>=6.12",
5454
"ipython",
5555
"mypy",
5656
"pre-commit",

0 commit comments

Comments
 (0)