# Create latex boolean from pythontex

I essentially want to do something like this.

\documentclass{scrartcl}

\usepackage{fontspec}

\usepackage[gobble=auto]{pythontex}
\usepackage{ifthen}

\begin{document}

\newboolean{tex_bool}

\begin{pycode}
py_bool = 3 == 4
set_cmd = r'\setboolean{tex_bool}{true}' if py_bool else r'\setboolean{tex_bool}{false}'
print(set_cmd)
\end{pycode}

The boolean was
\ifthenelse{\boolean{tex_bool}}{%
true
}{%
false
}

\end{document}


However, this does not work. Not reliably at least.

I think I should specify the order of expansions here. But I cannot figure out how. Is there a way to make this work?

• You should also explain what you mean by "not work reliably". If you mean it cause some error on first compilation, it's by design (you have to run the necessary passes, see doc) Jan 6 at 16:09
• Sry. I should have been more clear. It does compile but not always with the expected result. In this case actually never. In a different document of mine it sometimes seemed to work that why I came up with "reliably". Jan 6 at 19:07

Use \pyc for print.

\documentclass{scrartcl}

\usepackage{fontspec}

\usepackage[gobble=auto]{pythontex}
\usepackage{ifthen}

\begin{document}

\newboolean{tex_bool}

\begin{pycode}
py_bool = 3 == 3
set_cmd = r'\setboolean{tex_bool}{true}' if py_bool else r'\setboolean{tex_bool}{false}'
\end{pycode}
\pyc{print(set_cmd)}

The boolean was
\ifthenelse{\boolean{tex_bool}}{%
true
}{%
false
}

\end{document}

• I don't see how this could work better than the original code. Pycode is already a verbatim environment. Jan 6 at 16:09
• @user202729 Pycode is not a verbatim environment. It executes the codes. We need pdflatex, pythontex.py and pdflatex for get correct output. For testing you can change the py_bool = 3 == 3 condition to py_bool = 3 == 4 and see the changes. Jan 6 at 16:18
• By "verbatim environment" I mean that the content inside is grabbed as verbatim, so I see how csname is useful. Jan 6 at 16:20
• @user202729Did you mean in the first comment that the output of the answer and the question are the same? Or I misunderstood your mean? Jan 6 at 16:36
• I understood from the question that it does not give the correct output. Even when the py_bool is true (3 == 3). ‌But in answer, the output is correct; Both for py_bool=true and for py_bool=false. Jan 6 at 16:40