Change fragile code to pretty-print using black instead of pprint

This commit is contained in:
Gerard Vermeulen 2023-08-24 10:43:26 +02:00
parent f934eefb55
commit aca76d090c

View File

@ -2172,7 +2172,9 @@ list detailing and motivating each listing:
and it provides a function to remove the indentation of all =org-src-mode=
blocks without =-i= switch.
7. Listing [[lst:setup-ob-python]] allows to pretty-print Python session source
block values with [[https://github.com/psf/black#readme][black]] instead of [[https://docs.python.org/3/library/pprint.html][pprint]].
block values with [[https://github.com/psf/black#readme][black]] instead of [[https://docs.python.org/3/library/pprint.html][pprint]]. This snippet may break in the
future, because it sets =org-babel-python--def-format-value= which is a
constant declared "private" by two dashes in its name!
8. Listing [[lst:set-org-export-options]] selects the =non-intrusive= expert user
interface for export dispatching.
9. Listing [[lst:setup-org-for-lualatex-export]] and
@ -2382,42 +2384,53 @@ When called twice, replace the previously inserted \\(\\) by one $."
#+end_src
#+caption[Setup =ob-python=]:
#+caption: Setup =ob-python=.
#+caption: Setup =ob-python=. This snippet may break in the future!
#+name: lst:setup-ob-python
#+begin_src emacs-lisp -n :results silent
(with-eval-after-load 'ob-python
(defun org-babel-python-format-session-value-override
(src-file result-file result-params)
"Return Python code to evaluate SRC-FILE and write result to RESULT-FILE.
Use `black' instead of `pprint' when \"pp\" is a member of RESULT-PARAMS."
(format "\
import ast
with open('%s') as __org_babel_python_tmpfile:
__org_babel_python_ast = ast.parse(__org_babel_python_tmpfile.read())
__org_babel_python_final = __org_babel_python_ast.body[-1]
if isinstance(__org_babel_python_final, ast.Expr):
__org_babel_python_ast.body = __org_babel_python_ast.body[:-1]
exec(compile(__org_babel_python_ast, '<string>', 'exec'))
__org_babel_python_final = eval(
compile(ast.Expression(__org_babel_python_final.value), '<string>', 'eval')
)
with open('%s', 'w') as __org_babel_python_tmpfile:
if %s:
(setq org-babel-python--def-format-value "\
def __org_babel_python_format_value(result, result_file, result_params):
with open(result_file, 'w') as f:
if 'graphics' in result_params:
result.savefig(result_file)
elif 'pp' in result_params:
import black
__org_babel_python_tmpfile.write(
black.format_str(repr(__org_babel_python_final), mode=black.Mode())
)
f.write(black.format_str(repr(result), mode=black.Mode()))
elif 'list' in result_params and isinstance(result, dict):
f.write(str(['{} :: {}'.format(k, v) for k, v in result.items()]))
else:
__org_babel_python_tmpfile.write(str(__org_babel_python_final))
else:
exec(compile(__org_babel_python_ast, '<string>', 'exec'))
__org_babel_python_final = None"
(org-babel-process-file-name src-file 'noquote)
(org-babel-process-file-name result-file 'noquote)
(if (member "pp" result-params) "True" "False")))
(advice-add 'org-babel-python-format-session-value
:override #'org-babel-python-format-session-value-override))
if not set(result_params).intersection(\
['scalar', 'verbatim', 'raw']):
def dict2table(res):
if isinstance(res, dict):
return [(k, dict2table(v)) for k, v in res.items()]
elif isinstance(res, list) or isinstance(res, tuple):
return [dict2table(x) for x in res]
else:
return res
if 'table' in result_params:
result = dict2table(result)
try:
import pandas
except ImportError:
pass
else:
if isinstance(result, pandas.DataFrame) and 'table' in result_params:
result = [[result.index.name or ''] + list(result.columns)] + \
[None] + [[i] + list(row) for i, row in result.iterrows()]
elif isinstance(result, pandas.Series) and 'table' in result_params:
result = list(result.items())
try:
import numpy
except ImportError:
pass
else:
if isinstance(result, numpy.ndarray):
if 'table' in result_params:
result = result.tolist()
else:
result = repr(result)
f.write(str(result))"))
#+end_src
#+caption[Set =org-export= options]: