diff --git a/tests/snippets/warnings.py b/tests/snippets/warnings.py new file mode 100644 index 0000000000..95092e5066 --- /dev/null +++ b/tests/snippets/warnings.py @@ -0,0 +1,3 @@ +import _warnings + +_warnings.warn("Test") diff --git a/vm/src/stdlib/mod.rs b/vm/src/stdlib/mod.rs index ef2d7f3a53..096d148458 100644 --- a/vm/src/stdlib/mod.rs +++ b/vm/src/stdlib/mod.rs @@ -16,6 +16,7 @@ mod string; mod thread; mod time_module; mod tokenize; +mod warnings; mod weakref; use std::collections::HashMap; @@ -55,6 +56,7 @@ pub fn get_module_inits() -> HashMap { modules.insert("tokenize".to_string(), Box::new(tokenize::make_module)); modules.insert("_weakref".to_string(), Box::new(weakref::make_module)); modules.insert("_imp".to_string(), Box::new(imp::make_module)); + modules.insert("_warnings".to_string(), Box::new(warnings::make_module)); // disable some modules on WASM #[cfg(not(target_arch = "wasm32"))] diff --git a/vm/src/stdlib/warnings.rs b/vm/src/stdlib/warnings.rs new file mode 100644 index 0000000000..cb97ead480 --- /dev/null +++ b/vm/src/stdlib/warnings.rs @@ -0,0 +1,37 @@ +use crate::function::OptionalArg; +use crate::obj::objstr::PyStringRef; +use crate::pyobject::PyObjectRef; +use crate::vm::VirtualMachine; + +#[derive(FromArgs)] +struct WarnArgs { + #[pyarg(positional_only, optional = false)] + message: PyStringRef, + #[pyarg(positional_or_keyword, optional = true)] + category: OptionalArg, + #[pyarg(positional_or_keyword, optional = true)] + stacklevel: OptionalArg, +} + +fn warnings_warn(args: WarnArgs, _vm: &VirtualMachine) { + // TODO: Implement correctly + let level = match args.stacklevel { + OptionalArg::Present(l) => l, + OptionalArg::Missing => 1, + }; + eprintln!( + "Warning: {} , category: {:?}, level: {}", + args.message.as_str(), + args.category, + level + ) +} + +pub fn make_module(vm: &VirtualMachine) -> PyObjectRef { + let ctx = &vm.ctx; + let module = py_module!(vm, "_warnings", { + "warn" => ctx.new_rustfunc(warnings_warn), + }); + + module +}