Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to label Python code in LaTeX? [closed]

Tags:

latex

We have made a few examples of code in Python and inserted them into a LaTeX/overleaf document. We are currently looking into making a label for them, so they can be referenced at various points, however using the \begin(python) doesn't seem to allow us to add a \label{}, which works and can be referenced. A similar example of what we are looking for would be

\documentclass[11pt,a4paper,twoside,openany,english]{book}
\usepackage{pythonhighlight}

\begin{python}\label{SO-test}
    value_a = 1                   
    value_b = 2                    
    print(value_a + value_b)     
\end{python}

Any tips or tricks are appreciated.

like image 525
Jangog2276 Avatar asked Sep 01 '25 10:09

Jangog2276


1 Answers

Behind the scenes the pythonhighlight uses the much more common listings package. The listings package allows you to add a caption and label as optional argument of the lstlistings environment.

However even though the pythonhighlight sets up its python environment with the possibility to add an optional argument, it never uses this argument. Thus the information is never forwarded to the lstlistings environment.

To work around this, you can set up your own environment:

\documentclass[11pt,a4paper,twoside,openany,english]{book}
\usepackage{pythonhighlight}

\lstnewenvironment{mypython}[1][]{\lstset{style=mypython,#1}}{}

\begin{document}

\begin{mypython}[caption={some text to produce a caption},label=SO-test]
    value_a = 1                   
    value_b = 2                    
    print(value_a + value_b)     
\end{mypython}

Reference: \ref{SO-test}

\end{document}

enter image description here

like image 111
samcarter_is_at_topanswers.xyz Avatar answered Sep 05 '25 12:09

samcarter_is_at_topanswers.xyz