Shared prelude: turns inputs into Python variables and wraps the user code in a function so `return` works. `from X import *` lines are hoisted to module scope because Python 3 disallows them inside functions.
(user_code: &str, input: &Value)
| 204 | /// in a function so `return` works. `from X import *` lines are hoisted to |
| 205 | /// module scope because Python 3 disallows them inside functions. |
| 206 | fn build_user_block(user_code: &str, input: &Value) -> (String, String, String) { |
| 207 | let inputs_json = serde_json::to_string(input).unwrap_or_else(|_| "{}".into()); |
| 208 | let (star_imports, clean_code) = extract_star_imports(user_code); |
| 209 | let indented = indent_code(&clean_code, " "); |
| 210 | let var_setup = match input.as_object() { |
| 211 | Some(obj) => obj.keys() |
| 212 | .map(|k| { |
| 213 | let safe = sanitize_identifier(k); |
| 214 | format!("{} = __weft_inputs__.get({})", safe, python_str_literal(k)) |
| 215 | }) |
| 216 | .collect::<Vec<_>>() |
| 217 | .join("\n"), |
| 218 | None => String::new(), |
| 219 | }; |
| 220 | let prelude = format!( |
| 221 | "__weft_inputs__ = __weft_json__.loads({inputs})\n{vars}", |
| 222 | inputs = python_str_literal(&inputs_json), |
| 223 | vars = var_setup, |
| 224 | ); |
| 225 | (star_imports, prelude, indented) |
| 226 | } |
| 227 | |
| 228 | /// Build the full Python script that gets sent to E2B's /execute endpoint. |
| 229 | /// The function's return dict is rendered as the cell's last expression wrapped |
no test coverage detected