@@ -469,22 +469,26 @@ fn copy_context(py: Python) -> PyResult<Bound<PyAny>> {
469469 contextvars ( py) ?. call_method0 ( "copy_context" )
470470}
471471
472- /// Task-local data to store for Python conversions .
472+ /// Task-local inner structure .
473473#[ derive( Debug ) ]
474- pub struct TaskLocals {
474+ struct TaskLocalsInner {
475475 /// Track the event loop of the Python task
476- event_loop : Arc < Py < PyAny > > ,
476+ event_loop : Py < PyAny > ,
477477 /// Track the contextvars of the Python task
478- context : Arc < Py < PyAny > > ,
478+ context : Py < PyAny > ,
479479}
480480
481+ /// Task-local data to store for Python conversions.
482+ #[ derive( Debug ) ]
483+ pub struct TaskLocals ( Arc < TaskLocalsInner > ) ;
484+
481485impl TaskLocals {
482486 /// At a minimum, TaskLocals must store the event loop.
483487 pub fn new ( event_loop : Bound < PyAny > ) -> Self {
484- Self {
485- context : Arc :: new ( event_loop. py ( ) . None ( ) ) ,
486- event_loop : Arc :: new ( event_loop. into ( ) ) ,
487- }
488+ Self ( Arc :: new ( TaskLocalsInner {
489+ context : event_loop. py ( ) . None ( ) ,
490+ event_loop : event_loop. into ( ) ,
491+ } ) )
488492 }
489493
490494 /// Construct TaskLocals with the event loop returned by `get_running_loop`
@@ -494,10 +498,10 @@ impl TaskLocals {
494498
495499 /// Manually provide the contextvars for the current task.
496500 pub fn with_context ( self , context : Bound < PyAny > ) -> Self {
497- Self {
498- context : Arc :: new ( context. into ( ) ) ,
499- .. self
500- }
501+ Self ( Arc :: new ( TaskLocalsInner {
502+ event_loop : self . 0 . event_loop . clone_ref ( context. py ( ) ) ,
503+ context : context . into ( ) ,
504+ } ) )
501505 }
502506
503507 /// Capture the current task's contextvars
@@ -507,12 +511,12 @@ impl TaskLocals {
507511
508512 /// Get a reference to the event loop
509513 pub fn event_loop < ' p > ( & self , py : Python < ' p > ) -> Bound < ' p , PyAny > {
510- self . event_loop . clone_ref ( py) . into_bound ( py)
514+ self . 0 . event_loop . clone_ref ( py) . into_bound ( py)
511515 }
512516
513517 /// Get a reference to the python context
514518 pub fn context < ' p > ( & self , py : Python < ' p > ) -> Bound < ' p , PyAny > {
515- self . context . clone_ref ( py) . into_bound ( py)
519+ self . 0 . context . clone_ref ( py) . into_bound ( py)
516520 }
517521
518522 /// Create a clone of the TaskLocals. No longer uses the runtime, use `clone` instead.
@@ -526,10 +530,7 @@ impl Clone for TaskLocals {
526530 /// Create a clone of the TaskLocals by incrementing the reference counters of the event loop and
527531 /// contextvars.
528532 fn clone ( & self ) -> Self {
529- Self {
530- event_loop : self . event_loop . clone ( ) ,
531- context : self . context . clone ( ) ,
532- }
533+ Self ( self . 0 . clone ( ) )
533534 }
534535}
535536
0 commit comments