@@ -66,9 +66,35 @@ impl Context {
66
66
}
67
67
68
68
fn try_new ( py : Python ) -> PyResult < Self > {
69
- Ok ( Self {
70
- globals : py. import ( "__main__" ) ?. dict ( ) . copy ( ) ?. into ( ) ,
71
- } )
69
+ let rust_vars = PyDict :: new ( py) ;
70
+ let globals = PyDict :: new ( py) ;
71
+ let ctx = Self { globals : globals. into ( ) } ;
72
+ ctx. run_with_gil (
73
+ py,
74
+ inline_python_macros:: python! {
75
+ class RustVars :
76
+ __slots__ = ( "_dict" , "_mutable" )
77
+ def __init__( self , mutable: bool ) :
78
+ self . _dict = dict( )
79
+ self . _mutable = mutable
80
+
81
+ def __setitem__( self , key, value) :
82
+ if self . _mutable:
83
+ self . _dict[ key] = value
84
+ else:
85
+ raise TypeError ( "You are trying to write to " +'\'' +key+" which is read-only. Try #" +key)
86
+
87
+ def __getitem__( self , key) :
88
+ return self . _dict[ key]
89
+
90
+ _RUST_MUT_VARS = RustVars ( True )
91
+ _RUST_IMMUT_VARS = RustVars ( False )
92
+
93
+ del RustVars
94
+ from builtins import *
95
+ } ,
96
+ ) ;
97
+ Ok ( ctx)
72
98
}
73
99
74
100
/// Get the globals as dictionary.
@@ -192,7 +218,16 @@ impl Context {
192
218
///
193
219
/// This function panics if the Python code fails.
194
220
pub fn run_with_gil < F : FnOnce ( & PyDict ) > ( & self , py : Python < ' _ > , code : PythonBlock < F > ) {
195
- ( code. set_variables ) ( self . globals ( py) ) ;
221
+ let immut_vars = self
222
+ . globals ( py)
223
+ . get_item ( "_RUST_IMMUT_VARS" )
224
+ . unwrap ( )
225
+ . getattr ( "_dict" )
226
+ . unwrap ( )
227
+ . cast_as :: < PyDict > ( )
228
+ . unwrap ( ) ;
229
+
230
+ ( code. set_variables ) ( & immut_vars) ;
196
231
match run_python_code ( py, self , code. bytecode ) {
197
232
Ok ( _) => ( ) ,
198
233
Err ( e) => {
@@ -201,4 +236,8 @@ impl Context {
201
236
}
202
237
}
203
238
}
239
+
240
+ pub fn try_run < F : FnOnce ( & PyDict ) > ( & self , code : PythonBlock < F > ) -> Result < ( ) , pyo3:: PyErr > {
241
+ todo ! ( ) ;
242
+ }
204
243
}
0 commit comments