While restricted code may be completely self-contained, it's common for it to require other data: perhaps a tuple listing various available plug-ins, or a dictionary mapping symbols to values. For simple Python data types, such as numbers and strings, the natural solution is to insert variables into one of the namespaces used by the restricted environment, binding the desired variable name to the value.
Continuing from the examples above, you can get the dictionary
corresponding to the restricted module named module_name
with the
following code:
module = r_env.add_module(module_name) mod_dict = module.__dict__
Despite its name, the add_module()
method actually only adds the
module if it doesn't already exist; it returns the corresponding module
object, whether or not the module had to be created.
Most commonly, you'll insert variable bindings into the __main__
or __builtins__
module, so these will be the most frequent values
of module_name
.
Once you have the module's dictionary, you need only insert a key/value
pair for the desired variable name and value. For example, to add a
username
variable:
mod_dict['username'] = "Kate Bush"
Restricted code will then have access to this variable.