Skip to content

Commit

Permalink
Defer creation of ready future (#858)
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 authored Oct 19, 2022
1 parent 30cbf97 commit a438592
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 15 deletions.
30 changes: 16 additions & 14 deletions jupyter_client/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ class _ShutdownStatus(Enum):
F = t.TypeVar('F', bound=t.Callable[..., t.Any])


def _get_future() -> t.Union[Future, CFuture]:
"""Get an appropriate Future object"""
try:
asyncio.get_running_loop()
return Future()
except RuntimeError:
# No event loop running, use concurrent future
return CFuture()


def in_pending_state(method: F) -> F:
"""Sets the kernel to a pending state by
creating a fresh Future for the KernelManager's `ready`
Expand All @@ -64,12 +74,8 @@ def in_pending_state(method: F) -> F:
@functools.wraps(method)
async def wrapper(self, *args, **kwargs):
# Create a future for the decorated method
if self._attempted_start:
try:
self._ready = Future()
except RuntimeError:
# No event loop running, use concurrent future
self._ready = CFuture()
if self._attempted_start or not self._ready:
self._ready = _get_future()
try:
# call wrapped method, await, and set the result or exception.
out = await method(self, *args, **kwargs)
Expand All @@ -91,19 +97,13 @@ class KernelManager(ConnectionFileMixin):
This version starts kernels with Popen.
"""

_ready: t.Union[Future, CFuture]
_ready: t.Optional[t.Union[Future, CFuture]]

def __init__(self, *args, **kwargs):
super().__init__(**kwargs)
self._shutdown_status = _ShutdownStatus.Unset
self._attempted_start = False
# Create a place holder future.
try:
asyncio.get_running_loop()
self._ready = Future()
except RuntimeError:
# No event loop running, use concurrent future
self._ready = CFuture()
self._ready = None

_created_context: Bool = Bool(False)

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

@property
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ Homepage = "https://jupyter.org"
test = [
"codecov",
"coverage",
"ipykernel>=6.5",
"ipykernel>=6.12",
"ipython",
"mypy",
"pre-commit",
Expand Down

0 comments on commit a438592

Please sign in to comment.