@@ -24,12 +24,12 @@ thread_local! {
2424mod _contextvars {
2525 use crate :: vm:: {
2626 AsObject , Py , PyObjectRef , PyPayload , PyRef , PyResult , VirtualMachine , atomic_func,
27- builtins:: { PyGenericAlias , PyStrRef , PyType , PyTypeRef } ,
27+ builtins:: { PyGenericAlias , PyList , PyStrRef , PyType , PyTypeRef } ,
2828 class:: StaticType ,
2929 common:: hash:: PyHash ,
3030 function:: { ArgCallable , FuncArgs , OptionalArg } ,
3131 protocol:: { PyMappingMethods , PySequenceMethods } ,
32- types:: { AsMapping , AsSequence , Constructor , Hashable , Representable } ,
32+ types:: { AsMapping , AsSequence , Constructor , Hashable , Iterable , Representable } ,
3333 } ;
3434 use core:: {
3535 cell:: { Cell , RefCell , UnsafeCell } ,
@@ -163,7 +163,7 @@ mod _contextvars {
163163 }
164164 }
165165
166- #[ pyclass( with( Constructor , AsMapping , AsSequence ) ) ]
166+ #[ pyclass( with( Constructor , AsMapping , AsSequence , Iterable ) ) ]
167167 impl PyContext {
168168 #[ pymethod]
169169 fn run (
@@ -205,11 +205,6 @@ mod _contextvars {
205205 self . borrow_vars ( ) . len ( )
206206 }
207207
208- #[ pymethod]
209- fn __iter__ ( & self ) -> PyResult {
210- unimplemented ! ( "Context.__iter__ is currently under construction" )
211- }
212-
213208 #[ pymethod]
214209 fn get (
215210 & self ,
@@ -238,6 +233,15 @@ mod _contextvars {
238233 let vars = zelf. borrow_vars ( ) ;
239234 vars. values ( ) . map ( |value| value. to_owned ( ) ) . collect ( )
240235 }
236+
237+ // TODO: wrong return type
238+ #[ pymethod]
239+ fn items ( zelf : PyRef < Self > , vm : & VirtualMachine ) -> Vec < PyObjectRef > {
240+ let vars = zelf. borrow_vars ( ) ;
241+ vars. iter ( )
242+ . map ( |( k, v) | vm. ctx . new_tuple ( vec ! [ k. clone( ) . into( ) , v. clone( ) ] ) . into ( ) )
243+ . collect ( )
244+ }
241245 }
242246
243247 impl Constructor for PyContext {
@@ -281,6 +285,15 @@ mod _contextvars {
281285 }
282286 }
283287
288+ impl Iterable for PyContext {
289+ fn iter ( zelf : PyRef < Self > , vm : & VirtualMachine ) -> PyResult {
290+ let vars = zelf. borrow_vars ( ) ;
291+ let keys: Vec < PyObjectRef > = vars. keys ( ) . map ( |k| k. clone ( ) . into ( ) ) . collect ( ) ;
292+ let list = vm. ctx . new_list ( keys) ;
293+ <PyList as Iterable >:: iter ( list, vm)
294+ }
295+ }
296+
284297 #[ pyattr]
285298 #[ pyclass( name, traverse) ]
286299 #[ derive( PyPayload ) ]
@@ -574,6 +587,22 @@ mod _contextvars {
574587 ) -> PyGenericAlias {
575588 PyGenericAlias :: from_args ( cls, args, vm)
576589 }
590+
591+ #[ pymethod]
592+ fn __enter__ ( zelf : PyRef < Self > ) -> PyRef < Self > {
593+ zelf
594+ }
595+
596+ #[ pymethod]
597+ fn __exit__ (
598+ zelf : & Py < Self > ,
599+ _ty : PyObjectRef ,
600+ _val : PyObjectRef ,
601+ _tb : PyObjectRef ,
602+ vm : & VirtualMachine ,
603+ ) -> PyResult < ( ) > {
604+ ContextVar :: reset ( & zelf. var , zelf. to_owned ( ) , vm)
605+ }
577606 }
578607
579608 impl Constructor for ContextToken {
0 commit comments