# Typeset functions with PythonTeX and execute them in console afterwards

I have the following python source code:

def modulo(a, n):
return a % n

print(modulo(3, 10))
print(modulo(10, 10))
print(modulo(11, 10))


The first function definition gives a hint about the implementation and the calls below show exemplary usage / output.

I want to typeset this the following way (so people can copy&paste the implementation and see some live output):

def modulo(a, n):
return a % n

>>> print(modulo(3, 10))
3
>>> print(modulo(10, 10))
0
>>> print(modulo(11, 10))
1


I failed to create this using PythonTeX.

\begin{pyblock}[mysession][]
def modulo(a, n):
return a % n

\end{pyblock}

\begin{pyconsole}[mysession][]
print(modulo(3, 10))
print(modulo(10, 10))
print(modulo(11, 10))

\end{pyconsole}


This gives me

def modulo(a, n):
return a % n

>>> print(modulo(3, 10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'modulo' is not defined
>>> print(modulo(10, 10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'modulo' is not defined
>>> print(modulo(11, 10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'modulo' is not defined


The documentation mentions sessions, where code is run in parallel so I put those code snippets explicitly into the same session (even though per default both are run in default).

I definitely need a PythonTeX solution. Any ideas?

Console code and normal code each have their own separate default sessions. All commands/environments starting with pycon execute completely separately from those beginning with py. There is no overlap between them.

A feature to do what you want has been requested and will be implemented in an upcoming release of PythonTeX. In the meantime, you can probably do what you want with this workaround, copied from that feature request.

\documentclass{article}

\usepackage{pythontex}

\newenvironment{pyconcodeblock}%
{\VerbatimEnvironment
\begin{VerbatimOut}{temp.py}}%
{\end{VerbatimOut}%
\inputpygments{python}{temp.py}}

\begin{document}

\begin{pyconcodeblock}
def foo(x):
return 2*x
\end{pyconcodeblock}

\begin{pyconsole}
x = 10
foo(x)
\end{pyconsole}

\end{document}

• Perfect answer resolving my session confusion and providing a workaround. The workaround does not work for me. Either the file temp.py does not exist or an AttributeError is raised. But this will be discussed on github. Thanks! Apr 27 '15 at 13:16