@@ -532,7 +532,8 @@ def make_pathsim_model(graph_data: dict) -> tuple[Simulation, float]:
532532 global_namespace = make_global_variables (global_vars )
533533
534534 # Create a combined namespace that includes built-in functions and global variables
535- eval_namespace = {** globals (), ** global_namespace }
535+ eval_namespace = globals ().copy ()
536+ eval_namespace .update (global_namespace )
536537
537538 solver_prms , extra_params , duration = make_solver_params (
538539 solver_prms , eval_namespace
@@ -554,6 +555,18 @@ def make_pathsim_model(graph_data: dict) -> tuple[Simulation, float]:
554555 for node in nodes :
555556 var_name = make_var_name (node )
556557 eval_namespace [var_name ] = find_block_by_id (node ["id" ], blocks )
558+
559+ # Execute python code
560+ # NOTE Rem: we execute it after creating blocks so that user code can reference blocks by their var names
561+ # ideally we would execute this just after `make_global_variables` so that global variables can be defined in the code editor
562+ # but I couldn't get it to work, it must be a namespace issue
563+ python_code = graph_data .get ("pythonCode" , "" )
564+ if python_code :
565+ try :
566+ exec (python_code , eval_namespace )
567+ except Exception as e :
568+ return jsonify ({"error" : f"Error executing Python code: { str (e )} " }), 400
569+
557570 events += make_events (graph_data .get ("events" , []), eval_namespace )
558571
559572 # Create the simulation
0 commit comments