Skip to content

Commit aa155a1

Browse files
committed
Allow builtins to be overrided by parameter
1 parent be462af commit aa155a1

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

vm/src/builtins.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -735,7 +735,7 @@ fn builtin_zip(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
735735

736736
// builtin___import__
737737

738-
pub fn make_module(ctx: &PyContext) -> PyObjectRef {
738+
pub fn make_module(ctx: &PyContext, builtin_overrides: HashMap<String, PyObjectRef>) -> PyObjectRef {
739739
// scope[String::from("print")] = print;
740740
let mut dict = HashMap::new();
741741
//set __name__ fixes: https://github.com/RustPython/RustPython/issues/146
@@ -840,6 +840,10 @@ pub fn make_module(ctx: &PyContext) -> PyObjectRef {
840840
ctx.exceptions.value_error.clone(),
841841
);
842842

843+
for (name, py_object) in builtin_overrides {
844+
dict.insert(name, py_object);
845+
}
846+
843847
let d2 = PyObject::new(PyObjectKind::Dict { elements: dict }, ctx.type_type());
844848
let scope = PyObject::new(
845849
PyObjectKind::Scope {
@@ -897,3 +901,26 @@ pub fn builtin_build_class_(vm: &mut VirtualMachine, mut args: PyFuncArgs) -> Py
897901

898902
vm.call_method(&metaclass, "__call__", vec![name_arg, bases, namespace])
899903
}
904+
905+
#[cfg(test)]
906+
mod tests {
907+
use super::*;
908+
use super::super::pyobject::PyContext;
909+
910+
#[test]
911+
fn test_make_module() {
912+
let ctx = PyContext::new();
913+
let builtin_module = make_module(&ctx, HashMap::new());
914+
assert!(builtin_module.get_attr("print").is_some());
915+
}
916+
917+
#[test]
918+
fn test_make_module_override() {
919+
let ctx = PyContext::new();
920+
let mut overrides = HashMap::new();
921+
overrides.insert(String::from("test_function"), ctx.object());
922+
let builtin_module = make_module(&ctx, overrides);
923+
assert!(builtin_module.get_attr("test_function").is_some());
924+
}
925+
926+
}

vm/src/vm.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ impl VirtualMachine {
4242
/// Create a new `VirtualMachine` structure.
4343
pub fn new() -> VirtualMachine {
4444
let ctx = PyContext::new();
45-
let builtins = builtins::make_module(&ctx);
45+
let builtins = builtins::make_module(&ctx, HashMap::new());
4646
let sysmod = sysmodule::mk_module(&ctx);
4747
// Add builtins as builtins module:
4848
// sysmod.get_attr("modules").unwrap().set_item("builtins", builtins.clone());

0 commit comments

Comments
 (0)