From 6149b6cb6d648538be36bcf22c9adbf5a57c29bd Mon Sep 17 00:00:00 2001 From: Jack Kamm Date: Sun, 24 May 2020 07:40:11 -0700 Subject: [PATCH] ob-python.el: Assign variables in preamble instead of body * lisp/ob-python.el (org-babel-execute:python): Add variable assignment to preamble instead of body. (org-babel-python-evaluate): Concatenate preamble (which now includes variable assignment) to body before session evaluation. Fixes https://lists.gnu.org/archive/html/emacs-orgmode/2020-03/msg00126.html. For non-session evaluation, ob-python adds indentation to the body inside main(), but this was adding spurious indentation for multiline strings passed through :var. This commit fixes the issue by moving variable assignment out of the body and into the preamble. --- lisp/ob-python.el | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/lisp/ob-python.el b/lisp/ob-python.el index dbcfac08d..fbc4e969f 100644 --- a/lisp/ob-python.el +++ b/lisp/ob-python.el @@ -82,10 +82,14 @@ This function is called by `org-babel-execute-src-block'." (return-val (when (and (eq result-type 'value) (not session)) (cdr (assq :return params)))) (preamble (cdr (assq :preamble params))) + (preamble (concat preamble (and preamble "\n") + (mapconcat #'identity + (org-babel-variable-assignments:python params) + "\n"))) (full-body (org-babel-expand-body:generic (concat body (if return-val (format "\nreturn %s" return-val) "")) - params (org-babel-variable-assignments:python params))) + params)) (result (org-babel-python-evaluate session full-body result-type result-params preamble))) (org-babel-reassemble-table @@ -272,7 +276,8 @@ except Exception: "Evaluate BODY as Python code." (if session (org-babel-python-evaluate-session - session body result-type result-params) + session (concat preamble (and preamble "\n") body) + result-type result-params) (org-babel-python-evaluate-external-process body result-type result-params preamble)))