How to fix pypy3 pip install fatal error: Python.h: No such file or directory

Problem

When trying to pip install pandas within a pypy3 virtualenv, you see an error message such as

      src/_imagingft.c:22:10: fatal error: Python.h: No such file or directory
         22 | #include "Python.h"
            |          ^~~~~~~~~~
      compilation terminated.
      building 'PIL._imagingmath' extension
      gcc -pthread -DNDEBUG -O2 -fPIC -I/usr/include/openjpeg-2.4 -I/usr/include/x86_64-linux-gnu -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/harfbuzz -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/fribidi -I/usr/local/include -I/usr/include -I/home/uli/pypyvenv/include -I/usr/include/pypy3.8 -c src/_imagingmath.c -o build/temp.linux-x86_64-pypy38/src/_imagingmath.o
      In file included from src/Tk/../libImaging/Imaging.h:13,
                       from src/Tk/tkImaging.c:42:
      src/Tk/../libImaging/ImPlatform.h:10:10: fatal error: Python.h: No such file or directory
         10 | #include "Python.h"
            |          ^~~~~~~~~~
      compilation terminated.
      building 'PIL._imagingmorph' extension
      gcc -pthread -DNDEBUG -O2 -fPIC -I/usr/include/openjpeg-2.4 -I/usr/include/x86_64-linux-gnu -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/harfbuzz -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/fribidi -I/usr/local/include -I/usr/include -I/home/uli/pypyvenv/include -I/usr/include/pypy3.8 -c src/_imagingmorph.c -o build/temp.linux-x86_64-pypy38/src/_imagingmorph.o
      src/_webp.c:2:10: fatal error: Python.h: No such file or directory
          2 | #include <Python.h>
            |          ^~~~~~~~~~
      compilation terminated.
      src/_imagingmorph.c:14:10: fatal error: Python.h: No such file or directory
         14 | #include "Python.h"
            |          ^~~~~~~~~~
      compilation terminated.
      src/_imaging.c:75:10: fatal error: Python.h: No such file or directory
         75 | #include "Python.h"
            |          ^~~~~~~~~~
      compilation terminated.
      src/_imagingmath.c:16:10: fatal error: Python.h: No such file or directory
         16 | #include "Python.h"
            |          ^~~~~~~~~~
      compilation terminated.
      error: command '/usr/bin/gcc' failed with exit code 1
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for pillow
Failed to build pandas pillow
ERROR: Could not build wheels for pandas, pillow, which is required to install pyproject.toml-based projects

Solution

You need to install pypy3-dev which contains the pypy3 development headers. Installing python3-dev doesn’t work here since you’re working in a pypy3 environment.

sudo apt -y install pypy3-dev