@@ -55,6 +55,16 @@ class _ShutdownStatus(Enum):
5555F = t .TypeVar ('F' , bound = t .Callable [..., t .Any ])
5656
5757
58+ def _get_future () -> t .Union [Future , CFuture ]:
59+ """Get an appropriate Future object"""
60+ try :
61+ asyncio .get_running_loop ()
62+ return Future ()
63+ except RuntimeError :
64+ # No event loop running, use concurrent future
65+ return CFuture ()
66+
67+
5868def in_pending_state (method : F ) -> F :
5969 """Sets the kernel to a pending state by
6070 creating a fresh Future for the KernelManager's `ready`
@@ -65,12 +75,8 @@ def in_pending_state(method: F) -> F:
6575 @functools .wraps (method )
6676 async def wrapper (self , * args , ** kwargs ):
6777 # Create a future for the decorated method
68- if self ._attempted_start :
69- try :
70- self ._ready = Future ()
71- except RuntimeError :
72- # No event loop running, use concurrent future
73- self ._ready = CFuture ()
78+ if self ._attempted_start or not self ._ready :
79+ self ._ready = _get_future ()
7480 try :
7581 # call wrapped method, await, and set the result or exception.
7682 out = await method (self , * args , ** kwargs )
@@ -92,19 +98,13 @@ class KernelManager(ConnectionFileMixin):
9298 This version starts kernels with Popen.
9399 """
94100
95- _ready : t .Union [Future , CFuture ]
101+ _ready : t .Optional [ t . Union [Future , CFuture ] ]
96102
97103 def __init__ (self , * args , ** kwargs ):
98104 super ().__init__ (** kwargs )
99105 self ._shutdown_status = _ShutdownStatus .Unset
100106 self ._attempted_start = False
101- # Create a place holder future.
102- try :
103- asyncio .get_running_loop ()
104- self ._ready = Future ()
105- except RuntimeError :
106- # No event loop running, use concurrent future
107- self ._ready = CFuture ()
107+ self ._ready = None
108108
109109 _created_context : Bool = Bool (False )
110110
@@ -189,6 +189,8 @@ def _default_cache_ports(self) -> bool:
189189 @property
190190 def ready (self ) -> t .Union [CFuture , Future ]:
191191 """A future that resolves when the kernel process has started for the first time"""
192+ if not self ._ready :
193+ self ._ready = _get_future ()
192194 return self ._ready
193195
194196 @property
0 commit comments