Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Defer creation of ready future #858

Merged
merged 2 commits into from
Oct 19, 2022
Merged
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
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