Build and Install Python on Raspberrian

How to build and install the latest version of Python on a standard Raspberrian image using the Raspberry Pi.

Tested on Raspberry Pi 3B+ and Raspberrian 4.14.98-v7+.

 Special things I've done which improve the speed and reliability of build:

  1. Used a fast SD card (Samsung class 10).
  2. Increased the swap size to 2G.
Things that are not standard on Raspberrian that need to be installed:
  1. bz2 development package
  2. dbm development package
  3. lzma development package*
  4. tkinter development package
  5. curses development package
  6. gdbm development package
  7. sqlite3 development package
  8. uuid development package
  9. curses_panel development package
  10. hashlib development package
  11. ssl development package
  12. readline development package
  13. libffi development package
  14. python-ctypeslib (may be unnecessary)
The tkinter package is probably not necessary as it is very old despite being standard. There does not appear to be a standard package called dbm. There does not appear to be a standard package called curses_panel. There does not appear to be a standard hashlib package.
Install command:
sudo apt install libbz2-dev lzma-dev libncurses5-dev libgdbm-dev libsqlite3-dev uuid-dev libssl-dev libreadline-dev libffi-dev python-ctypeslib

Then download the source and follow the standard python instructions.

Built 3.7.3 successfully with profile guided optimization and without tkinter. All tests passed.

*Still did not build the lzma module in python 3.7.3. Not sure why.