Put a letter-aligned grid behind a minted source code snippet?

If I may add an alternative solution:

Combining Box around minted environment with Generating grid in a box it is possible to achieve what the OP desires in an even more automatic way. The solution uses tcolorbox to create the box and etoolbox to "patch" the box around every minted environment.

The below MWE produces:

enter image description here

I'm not a huge user of tcolorbox so that may have room for improvement (which is welcome, of course)

MWE

\documentclass{article}

\usepackage{minted}
\usepackage[most]{tcolorbox}
\usepackage{etoolbox}

\newtcolorbox{mybox}{
breakable, enhanced,
arc=0pt, outer arc=0pt, %sets rounded corners to sharp
frame empty, %removes frame line
boxsep=0pt, left=0pt, top=0pt, bottom=0pt, %inner margins
colback=white, %backgound color
underlay={
    \begin{tcbclipinterior}
        \draw[help lines,
              xstep=0.525em,
              ystep=\baselineskip,
              shift={([yshift=0.25\baselineskip]interior.north west)}]
        (interior.south west) grid (interior.north east);
    \end{tcbclipinterior}
    }
}

\BeforeBeginEnvironment{minted}{\begin{mybox}}%
\AfterEndEnvironment{minted}{\end{mybox}}%
    
\begin{document}
    
\begin{minted}{py}
def f(x):
    y = x + 123456789012345678901234567879
    return y
\end{minted}

\end{document}

Remove the yshift from the draw commands and add the shift to the options of tikzpicture.

\begin{tikzpicture}%
  [remember picture, overlay,
   xshift=-0.45em,yshift=-0.25\baselineskip
  ]

enter image description here

\documentclass{article}
\usepackage{minted}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\usetikzlibrary{backgrounds}

\newcommand\DrawGrid[2]{%
\begin{tikzpicture}%
  [remember picture, overlay,
   xshift=-0.45em,yshift=-0.25\baselineskip
  ]
  \draw[help lines]   
  (pic cs:#1) 
  grid [xstep=0.525em, ystep = \baselineskip] 
  ([xshift=+60em]pic cs:#2);
\end{tikzpicture}%
}

\begin{document}

\begin{minted}[escapeinside=??]{py}
?\tikzmark{start}?
def f(x):
    y = x + 123456789012345678901234567879
    return y 
?\tikzmark{end}? 
\end{minted}

\DrawGrid{start}{end}

\end{document}