JelteF / PyLaTeX

A Python library for creating LaTeX files
https://jeltef.github.io/PyLaTeX/
MIT License
2.24k stars 287 forks source link

pylatex should not modify the data list passed #336

Open bersbersbers opened 2 years ago

bersbersbers commented 2 years ago

I was wondering why this code

import pylatex

data = ["Hello world."]
for i in range(10):
    pylatex.Document(data=data).generate_tex()

was generating this:

\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
%
%
%
\begin{document}%
Hello world.%
\normalsize%
\normalsize%
\normalsize%
\normalsize%
\normalsize%
\normalsize%
\normalsize%
\normalsize%
\normalsize%
\normalsize%
\end{document}

The reason seems to be that pylatex appends stuff to the commands argument without making a copy first, thus modifying the external list as can be seen here:

import pylatex

data = ["Hello world."]
for i in range(10):
    print(commands[-1])
    pylatex.Document(data=data).generate_tex()

image

A workaround is to call Document(..., data=["Hello world!"]) or Document(..., data=tuple(data)) or Document(..., data=data.copy()), but that should not be necessary.