1616import typing as t
1717import uuid
1818import warnings
19+ from contextvars import ContextVar
1920from datetime import datetime
2021from functools import partial
2122from signal import SIGINT , SIGTERM , Signals , default_int_handler , signal
@@ -194,8 +195,10 @@ def _default_ident(self):
194195
195196 # track associations with current request
196197 _allow_stdin = Bool (False )
197- _parents : Dict [str , t .Any ] = Dict ({"shell" : {}, "control" : {}})
198- _parent_ident = Dict ({"shell" : b"" , "control" : b"" })
198+ _control_parent : Dict [str , t .Any ] = Dict ({})
199+ _control_parent_ident : bytes = b""
200+ _shell_parent : ContextVar [dict [str , Any ]]
201+ _shell_parent_ident : ContextVar [bytes ]
199202
200203 @property
201204 def _parent_header (self ):
@@ -302,6 +305,14 @@ def __init__(self, **kwargs):
302305 self .do_execute , ["cell_meta" , "cell_id" ]
303306 )
304307
308+ self ._control_parent = {}
309+ self ._control_parent_ident = b""
310+
311+ self ._shell_parent = ContextVar ("shell_parent" )
312+ self ._shell_parent .set ({})
313+ self ._shell_parent_ident = ContextVar ("shell_parent_ident" )
314+ self ._shell_parent_ident .set (b"" )
315+
305316 async def dispatch_control (self , msg ):
306317 """Dispatch a control request, ensuring only one message is processed at a time."""
307318 # Ensure only one control message is processed at a time
@@ -737,8 +748,12 @@ def set_parent(self, ident, parent, channel="shell"):
737748 The parent identity is used to route input_request messages
738749 on the stdin channel.
739750 """
740- self ._parent_ident [channel ] = ident
741- self ._parents [channel ] = parent
751+ if channel == "control" :
752+ self ._control_parent_ident = ident
753+ self ._control_parent = parent
754+ else :
755+ self ._shell_parent_ident .set (ident )
756+ self ._shell_parent .set (parent )
742757
743758 def get_parent (self , channel = None ):
744759 """Get the parent request associated with a channel.
@@ -763,7 +778,9 @@ def get_parent(self, channel=None):
763778 else :
764779 channel = "shell"
765780
766- return self ._parents .get (channel , {})
781+ if channel == "control" :
782+ return self ._control_parent
783+ return self ._shell_parent .get ()
767784
768785 def send_response (
769786 self ,
@@ -1424,7 +1441,7 @@ def getpass(self, prompt="", stream=None):
14241441 )
14251442 return self ._input_request (
14261443 prompt ,
1427- self ._parent_ident [ "shell" ] ,
1444+ self ._shell_parent_ident . get () ,
14281445 self .get_parent ("shell" ),
14291446 password = True ,
14301447 )
@@ -1441,7 +1458,7 @@ def raw_input(self, prompt=""):
14411458 raise StdinNotImplementedError (msg )
14421459 return self ._input_request (
14431460 str (prompt ),
1444- self ._parent_ident [ "shell" ] ,
1461+ self ._shell_parent_ident . get () ,
14451462 self .get_parent ("shell" ),
14461463 password = False ,
14471464 )
0 commit comments