Minted Python example inside beamer frames

beamermintedpython

I would like to include minted Python code examples in my Beamer slide decks. I found an example that worked outside the \frame environment. Perhaps that will be suitable for future reports/documentation, but it doesn't serve my more specific
use case.

Inside my tex file I have the following:

\documentclass[compress]{beamer}

\usetheme{Frankfurt}
\setbeamertemplate{page number in head/foot}[totalframenumber]

%% Change shape of bullets
\setbeamertemplate{itemize items}[circle]
\setbeamertemplate{enumerate items}[circle]
%%%

%% Import packages
\usepackage{tcolorbox}
\usepackage{graphicx}
\usepackage{xcolor}
\usepackage{colortbl}
\usepackage{amsmath}
\usepackage{pifont}
\usepackage{ccicons}
\usepackage{tikz}
\usetikzlibrary{mindmap}
\usepackage{smartdiagram}
\usepackage[linesnumbered,lined,commentsnumbered]{algorithm2e}
\usepackage{hyperref}
\tcbuselibrary{minted,skins,breakable}
%%%

\newtcblisting{pythoncode}[2][]{
  listing engine=minted,
  breakable,
  coltitle=UNBCGold,
  colback=black,
  colframe=UNBCGreen,
  listing only,
  minted style=colorful,
  minted language=python,
  minted options={numbersep=3mm,texcl=true,#1},
  left=5mm,enhanced,
  overlay={\begin{tcbclipinterior}\fill[black!25] (frame.south west)
            rectangle ([xshift=5mm]frame.north west);\end{tcbclipinterior}},
            #2,
}

\begin{frame}
    \frametitle{Premature Optimization}
    \begin{pythoncode}[linenos=true,]{title=Python Code Example}
    import glob
    \end{pythoncode}
\end{frame}

But I am getting an error: ! File ended while scanning use of \next. This issue can be localized to the use of pythoncode due to the fact that taking it outside the frame scope allows compilation (with poor floating placement behaviour). Which is to say the following change compiles the PDF:

\begin{frame}
    \frametitle{Premature Optimization}
\end{frame}

\begin{pythoncode}[linenos=true,]{title=Python Code Example}
import glob
\end{pythoncode}

As suggested in the comments, I tried a minted env after importing the minted package. I found a similar pattern. The following didn't compile:

\begin{frame}
    \frametitle{Premature Optimization}
    \begin{tcolorbox}
    \begin{minted}{python}
    import glob
    \end{minted}
    \end{tcolorbox}
\end{frame}

While moving the minted environment outside did compile (with undesirable placement of the tcolorbox):

\begin{frame}
    \frametitle{Premature Optimization}
\end{frame}

    \begin{tcolorbox}
    \begin{minted}{python}
    import glob
    \end{minted}
    \end{tcolorbox}

How can I construct a similar listing\tcolorobox around Python code examples that can exist within Beamer frames?

Best Answer

You need to use [fragile] for your frame:

\begin{frame}[fragile]
    \frametitle{Premature Optimization}
    \begin{pythoncode}[linenos=true,]{title=Python Code Example}
    import glob
    \end{pythoncode}
\end{frame}
Related Question