MCPcopy Create free account
hub / github.com/WeaveMindAI/weft / build_user_block

Function build_user_block

catalog/code/:exec/python/backend.rs:206–226  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

204/// in a function so `return` works. `from X import *` lines are hoisted to
205/// module scope because Python 3 disallows them inside functions.
206fn 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

Callers 2

build_e2b_pythonFunction · 0.85
build_local_pythonFunction · 0.85

Calls 3

extract_star_importsFunction · 0.85
indent_codeFunction · 0.85
sanitize_identifierFunction · 0.85

Tested by

no test coverage detected