@@ -535,6 +535,14 @@ def make_pathsim_model(graph_data: dict) -> tuple[Simulation, float]:
535535 eval_namespace = globals ().copy ()
536536 eval_namespace .update (global_namespace )
537537
538+ # Execute python code first to define any variables that blocks might need
539+ python_code = graph_data .get ("pythonCode" , "" )
540+ if python_code :
541+ try :
542+ exec (python_code , eval_namespace )
543+ except Exception as e :
544+ return jsonify ({"error" : f"Error executing Python code: { str (e )} " }), 400
545+
538546 solver_prms , extra_params , duration = make_solver_params (
539547 solver_prms , eval_namespace
540548 )
@@ -556,17 +564,6 @@ def make_pathsim_model(graph_data: dict) -> tuple[Simulation, float]:
556564 var_name = make_var_name (node )
557565 eval_namespace [var_name ] = find_block_by_id (node ["id" ], blocks )
558566
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-
570567 events += make_events (graph_data .get ("events" , []), eval_namespace )
571568
572569 # Create the simulation
0 commit comments