How to Install Python 3.12 on Ubuntu

Python 3.12 helps you build web applications with Django or FastAPI, run data science workflows with NumPy and Pandas, and automate system tasks through reliable scripting. Whether you need a development environment for new projects or a stable interpreter for production deployments, Python 3.12 delivers modern language features like improved f-strings and clearer error messages with upstream security support through October 2028.

By the end of this guide, you will have a working Python 3.12 installation with pip configured, virtual environments ready for project isolation, and verified core modules. Each Ubuntu LTS release uses a different installation method: Ubuntu 24.04 LTS installs from official repositories, Ubuntu 22.04 LTS uses the Deadsnakes PPA, and Ubuntu 26.04 LTS compiles from source. Follow the section that matches your release.

When to Choose Python 3.12 Over Newer Versions

Compare Python Releases for Ubuntu

Ubuntu 24.04 LTS ships Python 3.12 by default, while Ubuntu 26.04 LTS ships Python 3.13. Use the following comparison to decide when Python 3.12 offers the right balance of stability, support, and feature coverage.

Review the release comparison

Python VersionAvailability on UbuntuChoose It WhenTrade-offs
Python 3.8 on UbuntuDeadsnakes PPA for Ubuntu 22.04 LTS; source builds for newer LTS releasesLegacy applications pinned to EOL runtimes, transitional migrations, compatibility testingEnd-of-life October 2024, no upstream security patches, container isolation recommended
Python 3.10 on UbuntuUbuntu 22.04 LTS default, Deadsnakes PPA for 24.04 LTS, source builds for 26.04 LTSProduction fleets requiring security coverage through October 2026, tools certified against 3.10 binaries, Canonical Extended Security Maintenance planningFewer new features, 24.04 LTS users must add the PPA, newer libraries target 3.11+
Python 3.11 on UbuntuDeadsnakes PPA for Ubuntu 22.04 LTS and 24.04 LTS; source builds for 26.04 LTSCPU-bound workloads seeking runtime improvements, exception groups, TOML parsing, fine-grained error locationsNot default on any Ubuntu LTS, community-maintained PPA, some vendor SDKs still validating against 3.10
Python 3.12Ubuntu 24.04 LTS default, Deadsnakes PPA for 22.04 LTS, source build for 26.04 LTSNew projects, development workstations, f-string upgrades (PEP 701), per-interpreter GIL experimental feature, security support through October 2028Ubuntu 22.04 LTS users must add the PPA, some older third-party modules may need updates, newer features land first in 3.13
Python 3.13 on UbuntuDeadsnakes PPA for Ubuntu 22.04 LTS and 24.04 LTS; source builds for 26.04 LTSAdopting the free-threaded preview, using the newest typing changes, planning for support through October 2029Not in Ubuntu repositories, community packages lack guaranteed security SLAs, some third-party wheels may lag early releases
Python 3.14 on UbuntuDeadsnakes PPA for Ubuntu 22.04 LTS and 24.04 LTS as published; source builds for 26.04 LTSEarly adopters validating the newest runtime and planning for support through October 2030Not in Ubuntu repositories, PPA refresh cadence may lag security fixes, third-party wheels can trail initial releases

Choose the best fit for your release

Ubuntu 24.04 LTS users should install from official repositories for the cleanest update path. Ubuntu 22.04 LTS users can add the Deadsnakes PPA to run Python 3.12 alongside Python 3.10, while Ubuntu 26.04 LTS users need a source build because the default interpreter is Python 3.13. Choose older versions only when your tooling requires them, and choose newer versions when you need the latest language changes or free-threaded previews.

Pre-Flight Checklist

Before installing Python 3.12, confirm your system state to avoid redundant installs or missing disk space for source builds:

# Check if Python 3.12 is already installed
python3.12 --version 2>/dev/null && echo "Python 3.12 already present" || echo "Python 3.12 not found, safe to install"

# Confirm your Ubuntu version (target LTS releases only)
lsb_release -rs

# Check available disk space (source builds need 300+ MB)
df -h /usr/local

Example output for supported LTS releases:

22.04
24.04
26.04

On most systems, /usr/local resides on the root filesystem. Confirm you have at least 500 MB free for source builds (the compiled installation uses roughly 100 MB, but the build process needs working space):

Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1       250G   40G  198G  17% /

If Python 3.12 is already installed, skip to the “Work in Python 3.12 Virtual Environments” section unless you need to rebuild with custom flags.

Ubuntu keeps the system interpreter separate from any additional Python versions you install to protect system utilities. You can add Python 3.12 alongside the default Python 3.10 on 22.04 LTS or Python 3.13 on 26.04 LTS without conflicts, as long as you do not change /usr/bin/python3 or remove the system Python packages.

Key Reasons to Choose Python 3.12

Python 3.12 remains the best choice for:

  • Ubuntu 24.04 LTS default interpreter: Ships with Ubuntu 24.04 LTS and receives automatic security updates from Canonical through October 2028.
  • Modern language features: PEP 701 f-strings, improved error messages with exact column positions, per-interpreter GIL (experimental), per-item type hint configuration.
  • Runtime improvements: Optimized bytecode execution and reduced overhead compared to earlier LTS defaults.
  • Security support through October 2028: Five additional years of upstream security patches guarantee production-grade stability without forcing major version upgrades.
  • Broad framework support: Major frameworks such as Django, FastAPI, and NumPy support Python 3.12 and publish current wheels.

Choose Your Python 3.12 Installation Method

Each Ubuntu LTS release requires a different installation approach based on Python 3.12 availability. The table below summarizes your options based on your release.

MethodChannelVersionUpdatesBest For
Ubuntu repositories (24.04 LTS)Ubuntu PackagesDistribution defaultAutomatic via apt upgradeUbuntu 24.04 LTS systems that want Canonical security updates
Deadsnakes PPA (22.04 LTS)Deadsnakes PPACommunity-maintainedManual monitoring with apt upgradeUbuntu 22.04 LTS systems that need Python 3.12 alongside 3.10
Source buildPython.org sourceLatest 3.12.x releaseManual rebuildsUbuntu 26.04 LTS or custom prefixes and optimization flags

I recommend the official Ubuntu repository method for most users on Ubuntu 24.04 LTS because it keeps Python 3.12 aligned with Canonical updates. Use the Deadsnakes PPA only on Ubuntu 22.04 LTS, and compile from source on Ubuntu 26.04 LTS where Python 3.12 packages are unavailable.

This guide covers Ubuntu 22.04 LTS, 24.04 LTS, and 26.04 LTS. The Deadsnakes PPA publishes Python 3.12 packages only for Ubuntu 22.04 LTS (codename jammy). Ubuntu 26.04 LTS ships Python 3.13 as default and does not include Python 3.12 in its repositories, so compilation from source is the only option. Follow the section that matches your release.

Understand Support and Compatibility Limits

  • Ubuntu 24.04 LTS ships Python 3.12 natively: The official repositories include python3.12, python3.12-dev, and related packages. Ubuntu 22.04 LTS uses Python 3.10, so you need the Deadsnakes PPA for 3.12, while Ubuntu 26.04 LTS ships Python 3.13 and requires a source build for 3.12.
  • Deadsnakes PPA carries a “no guaranteed updates” disclaimer: The maintainer states explicitly that production teams using the Deadsnakes PPA must monitor CVEs themselves and be ready to recompile or sandbox workloads until patched packages land.
  • Ecosystem support is strong: Django 5.0+, FastAPI, SQLAlchemy 2.0, NumPy 2.0, and modern frameworks support Python 3.12 with current wheels. Verify compatibility if you rely on legacy libraries pinned to 3.10.

Python 3.12 reaches upstream end-of-life on 31 October 2028, per the official release schedule (PEP 693). For systems requiring guaranteed security support beyond that date, plan migrations to Python 3.13 (EOL October 2029) or Python 3.14 (EOL October 2030). Ubuntu 24.04 LTS receives Canonical’s Extended Security Maintenance through April 2034, extending system-level support after Python 3.12 upstream EOL.

Python 3.12 Pre-Installation Steps

Update System Before Proceeding

Before installing Python 3.12, update your system’s package lists to ensure all dependencies resolve correctly and you receive the latest security patches. This step is particularly important when adding third-party repositories like Deadsnakes or compiling software from source, as build tools and libraries frequently receive compatibility updates.

Open a terminal and run:

sudo apt update

Optionally, upgrade installed packages to prevent conflicts during Python 3.12 installation:

sudo apt upgrade

Install Python 3.12 on Ubuntu

The right method depends on your Ubuntu release: Ubuntu 24.04 LTS installs Python 3.12 from official repositories, Ubuntu 22.04 LTS uses the Deadsnakes PPA, and Ubuntu 26.04 LTS requires the source build section below.

Install Python 3.12 from Ubuntu Repositories (24.04 LTS)

Use this method on Ubuntu 24.04 LTS to receive Canonical security updates without adding a third-party repository:

sudo apt install python3.12 python3.12-venv python3.12-dev

Verify the installation:

python3.12 --version
Python 3.12.3

Run a smoke test to ensure core modules loaded correctly:

python3.12 -c "import ssl, sqlite3, bz2; print('Python 3.12 ready on Ubuntu')"
Python 3.12 ready on Ubuntu

Install Python 3.12 via Deadsnakes PPA

Use this method only on Ubuntu 22.04 LTS. Ubuntu 24.04 LTS should use the official repositories, and Ubuntu 26.04 LTS requires the source build section because the PPA does not publish 26.04 packages.

Install the PPA helper if it is not already present:

sudo apt install software-properties-common

Add the Deadsnakes PPA and refresh package lists:

sudo add-apt-repository ppa:deadsnakes/ppa -y
sudo apt update

The -y flag auto-confirms the prompt so the repository is added without interruption.

apt-cache policy python3.12
python3.12:
  Installed: (none)
  Candidate: 3.12.12-1+jammy1
  Version table:
     3.12.12-1+jammy1 500
        500 https://ppa.launchpadcontent.net/deadsnakes/ppa/ubuntu jammy/main amd64 Packages

Install Python 3.12 from the PPA:

sudo apt install python3.12 python3.12-venv python3.12-dev

The Deadsnakes PPA explicitly disclaims timely security updates. The maintainer states: “there’s no guarantee of timely updates in case of security problems or other issues.” Production systems that demand guaranteed security patching should prefer Ubuntu 24.04 LTS official repositories or a source build with your own security monitoring workflow. Use Deadsnakes only for development machines, testing environments, or non-critical workloads where you accept responsibility for tracking CVEs independently.

Verify the installation:

python3.12 --version
Python 3.12.12

Install Additional Python 3.12 Packages (Optional)

Install additional modules when your workflow demands debugging tools, GUI bindings, or compatibility layers. The core installation already includes python3.12-venv and python3.12-dev, so only add these if you need specific functionality. Package names differ between Ubuntu 24.04 LTS and Ubuntu 22.04 LTS.

python3.12-dbg provides debugging symbols for profiling, crash analysis, or gdb attachments:

sudo apt install python3.12-dbg

GNU dbm bindings (gdbm) install via versioned packages on 22.04 LTS and unversioned packages on 24.04 LTS:

Ubuntu 24.04 LTS:

sudo apt install python3-gdbm

Ubuntu 22.04 LTS (Deadsnakes PPA):

sudo apt install python3.12-gdbm

Tkinter GUI bindings follow the same naming pattern:

Ubuntu 24.04 LTS:

sudo apt install python3-tk

Ubuntu 22.04 LTS (Deadsnakes PPA):

sudo apt install python3.12-tk

Python 3.12 removed the legacy distutils module per PEP 632. The python3.12-distutils package does not exist on Ubuntu 24.04 or in the Deadsnakes PPA. Projects that still require distutils should migrate to setuptools (which includes a distutils compatibility layer) or use modern build tools like Poetry or Hatchling.

Combine multiple packages in one apt invocation to save time:

# Ubuntu 24.04 LTS
sudo apt install python3.12-dbg python3-gdbm python3-tk

# Ubuntu 22.04 LTS (Deadsnakes PPA)
sudo apt install python3.12-dbg python3.12-gdbm python3.12-tk

The python3.12-full meta-package is available on Ubuntu 24.04 and in the Deadsnakes PPA. Use python3.12-full if you want the full optional set for Python 3.12, while python3-full tracks the default interpreter on Ubuntu 24.04.

Compile Python 3.12 from Source on Ubuntu

Compile Python 3.12 manually on Ubuntu 26.04 LTS or when you need custom prefixes or independent upgrade cycles. Source builds install alongside Ubuntu’s system Python without overwriting /usr/bin/python3.

Download Python 3.12 Source Tarball

Download the latest 3.12.x release directly from python.org and keep it in a dedicated build directory in your home folder so updates are repeatable:

mkdir -p ~/python3.12-build
cd ~/python3.12-build
PY312_VERSION="$(curl -s https://www.python.org/ftp/python/ | grep -oE '3\.12\.[0-9]+' | sort -V | tail -1)"
if [ -z "$PY312_VERSION" ]; then
  echo "Error: could not determine the latest Python 3.12 release."
  exit 1
fi
echo "Downloading Python ${PY312_VERSION}..."
wget https://www.python.org/ftp/python/${PY312_VERSION}/Python-${PY312_VERSION}.tar.xz
wget https://www.python.org/ftp/python/${PY312_VERSION}/Python-${PY312_VERSION}.tar.xz.asc

Verify the GPG Signature

Python source releases are signed by Thomas Wouters, the release manager for Python 3.12. Import his public key and verify the tarball before extracting:

# Import the Python 3.12 release manager's key (Thomas Wouters)
curl -fsSL https://github.com/Yhg1s.gpg | gpg --import

# Verify the signature
gpg --verify Python-${PY312_VERSION}.tar.xz.asc Python-${PY312_VERSION}.tar.xz

Expected output confirming a valid signature:

gpg: Signature made Thu 09 Oct 2025 12:00:00 AM UTC
gpg:                using RSA key 7169605F62C751356D054A26A821E680E5FA6305
gpg: Good signature from "Thomas Wouters <thomas@python.org>"

Extract the verified tarball:

tar -xf Python-${PY312_VERSION}.tar.xz
cd Python-${PY312_VERSION}

If the discovery command cannot reach python.org (for example, on air-gapped hosts), check the Python.org downloads page for the latest 3.12.x maintenance release and substitute that version manually in the URLs. You can verify the SHA256 checksum on the downloads page as a fallback if GPG verification fails.

Install Build Dependencies

Before compiling, install the libraries required for SSL, compression, readline, Tk, and UUID support:

sudo apt install build-essential zlib1g-dev libncurses-dev libgdbm-dev libnss3-dev \
libssl-dev libsqlite3-dev libreadline-dev libffi-dev libbz2-dev liblzma-dev uuid-dev \
tk-dev pkg-config -y

The -y flag automatically confirms the installation prompt, which is useful for scripted builds.

These package names exist on Ubuntu 22.04 LTS, 24.04 LTS, and 26.04 LTS, so the same command works regardless of which release you are compiling on.

Configure and Build Python 3.12

With dependencies installed, compile Python with optimization flags and a custom prefix so it installs alongside the system interpreter:

./configure --enable-optimizations --with-lto --with-ensurepip=install --prefix=/usr/local/python3.12

The configure script checks your system for required libraries and build tools. Watch for lines confirming optional modules will be built:

checking for openssl/ssl.h in /usr... yes
checking for X509_VERIFY_PARAM_set1_host in libssl... yes
checking for --with-ssl-default-suites... python
checking for sqlite3.h... yes
checking for SQLITE_OMIT_COMPLETE in sqlite3.h... no
checking for lzma.h... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: creating Misc/python.pc

If configure reports missing headers (for example, checking for openssl/ssl.h... no), install the corresponding -dev package and rerun configure before proceeding.

Compile and Install

Compile Python using all available CPU cores, then install to the custom prefix:

make -j"$(nproc)"
sudo make altinstall

The --prefix flag installs Python under /usr/local/python3.12, --with-lto enables Link Time Optimization for slightly faster runtime performance, and --with-ensurepip=install bundles pip. Compilation takes 5-15 minutes depending on your hardware when --enable-optimizations is enabled because it runs the test suite to profile the build.

Using make altinstall instead of make install keeps /usr/bin/python3 untouched while adding /usr/local/python3.12/bin/python3.12.

Register Libraries and Test the Build

After compilation completes, point the dynamic linker at your custom installation, reload the cache, and create a convenience symlink:

echo '/usr/local/python3.12/lib' | sudo tee /etc/ld.so.conf.d/python3.12.conf
sudo ldconfig
sudo ln -sf /usr/local/python3.12/bin/python3.12 /usr/local/bin/python3.12

Verify the build and confirm critical modules compiled successfully:

python3.12 --version
python3.12 -c "import ssl, sqlite3, bz2; print('Source build is healthy')"
Python 3.12.12
Source build is healthy

If the second command fails, reinstall the missing -dev packages, rerun ./configure, and rebuild the installation.

Install Pip for Python 3.12

Pip availability depends on how you installed Python 3.12. Use the method below that matches your Ubuntu release and installation path.

Install Pip via APT (Ubuntu 24.04 LTS)

On Ubuntu 24.04 LTS, the python3-pip package targets Python 3.12 and keeps pip updated through APT:

sudo apt install python3-pip

Verify the installation:

python3.12 -m pip --version
pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.12)

Install Pip with ensurepip (PPA or Source Builds)

If you installed Python 3.12 from the Deadsnakes PPA or from source, use ensurepip to bootstrap pip in the Python 3.12 site-packages directory:

python3.12 -m ensurepip --upgrade
python3.12 -m pip --version
pip 25.0.1 from /usr/local/lib/python3.12/dist-packages/pip (python 3.12)

Pip versions vary by Ubuntu release and installation method. The APT-installed pip version tracks Canonical’s packaging cycle, while ensurepip bundles the pip version available when your Python installation was built.

Bootstrap Pip with get-pip.py

Alternatively, for air-gapped systems or custom builds, download the latest bootstrap script and execute it with Python 3.12:

wget https://bootstrap.pypa.io/get-pip.py
python3.12 get-pip.py
rm get-pip.py

This approach installs pip, setuptools, and wheel side by side. Keep the script up to date whenever you rerun the procedure.

Manage Packages with python3.12 -m pip

Once pip is installed, always call pip through the desired interpreter to avoid cross-version confusion:

python3.12 -m pip install package_name
python3.12 -m pip install --upgrade package_name
python3.12 -m pip uninstall package_name

Replace package_name with libraries such as numpy, fastapi, or django. For a comprehensive guide to managing packages, see Install pip on Ubuntu. Using python3.12 -m pip ensures you target Python 3.12; use a virtual environment to keep packages isolated from the system interpreter.

Ubuntu 24.04 LTS and 26.04 LTS mark the system Python as externally managed (PEP 668). If you run python3.12 -m pip install <package> against the system interpreter on those releases, pip will error unless you work inside a virtual environment or pass --break-system-packages. Use --break-system-packages only when you understand the risks because it bypasses apt protections and can break system tools. The Deadsnakes Python 3.12 packages on Ubuntu 22.04 LTS do not ship an externally managed marker.

Work in Python 3.12 Virtual Environments

Virtual environments prevent package conflicts between projects by providing isolated site-packages directories. For comprehensive coverage of virtual environment workflows, see the dedicated Python virtual environment guide for Ubuntu.

Create a Python 3.12 Virtual Environment

First, create a dedicated directory for your environments (for example ~/venvs) and provision a new one with python3.12:

python3.12 -m venv ~/venvs/py312

Replace ~/venvs/py312 with any path meaningful to your workflow.

Activate the Virtual Environment

Next, activate the environment so your shell points python and pip to the local installation:

source ~/venvs/py312/bin/activate

The prompt changes to include the environment name, indicating successful activation. Install packages as needed while the environment remains active.

Deactivate the Virtual Environment

When finished, exit the virtual environment by running:

deactivate

The shell returns to the system Python context, ensuring new sessions do not inherit the environment accidentally.

Troubleshooting Common Python 3.12 Installation Issues

Missing Development Headers During Compilation

If development headers are missing, Python builds but some standard library modules fail to import.

A common error looks like:

ModuleNotFoundError: No module named '_ssl'

Confirm which modules are failing:

python3.12 -c "import ssl, sqlite3, bz2"
ModuleNotFoundError: No module named '_ssl'

Install the missing headers and rebuild:

sudo apt install libssl-dev libbz2-dev libsqlite3-dev
./configure --enable-optimizations --with-lto --with-ensurepip=install --prefix=/usr/local/python3.12
make -j"$(nproc)"
sudo make altinstall

Verify the modules load correctly:

python3.12 -c "import ssl, sqlite3, bz2; print('Modules loaded')"
Modules loaded

Shared Library Linking Errors

When running python3.12 after source compilation, you may encounter an error stating that the shared library cannot be found.

python3.12: error while loading shared libraries: libpython3.12.so.1.0: cannot open shared object file: No such file or directory

First verify the library exists and note its path:

find /usr/local -name "libpython3.12.so*"

Example output:

/usr/local/python3.12/lib/libpython3.12.so.1.0

Register the library path and refresh the linker cache:

echo "/usr/local/python3.12/lib" | sudo tee /etc/ld.so.conf.d/python3.12.conf
sudo ldconfig

Verify the interpreter starts correctly:

python3.12 --version
Python 3.12.12

PIP Externally Managed Environment Errors

On Ubuntu 24.04 LTS and 26.04 LTS, pip blocks installs to the system interpreter (python3) without a virtual environment. This does not affect Python 3.12 installed from the Deadsnakes PPA or source.

error: externally-managed-environment

X This environment is externally managed
-> To install Python packages system-wide, try apt install
   xyz, where xyz is the package you are trying to
   install.

If you wish to install a Python package using pip, you must
create a virtual environment first.

Create a venv instead of bypassing protections:

python3 -m venv myproject_env
source myproject_env/bin/activate
pip install package-name

Only use --break-system-packages in disposable environments:

python3 -m pip install --break-system-packages package-name

APT Breaking After Installing Python 3.12 PPA

If apt update or apt install fails with Python-related errors after adding the Deadsnakes PPA, the /usr/bin/python3 symlink may have been changed. A typical error looks like:

ModuleNotFoundError: No module named 'apt_pkg'

Check the /usr/bin/python3 symlink:

ls -la /usr/bin/python3

Expected output by release:

22.04 LTS (Jammy):

lrwxrwxrwx 1 root root 10 Aug  8  2024 /usr/bin/python3 -> python3.10

24.04 LTS (Noble):

lrwxrwxrwx 1 root root 10 Nov 12 12:15 /usr/bin/python3 -> python3.12

26.04 LTS (Resolute):

lrwxrwxrwx 1 root root 10 Aug 21 15:18 /usr/bin/python3 -> python3.13

If the symlink points elsewhere, restore the original target for your release:

# Ubuntu 24.04 LTS
sudo ln -sf /usr/bin/python3.12 /usr/bin/python3

# Ubuntu 22.04 LTS
sudo ln -sf /usr/bin/python3.10 /usr/bin/python3

# Ubuntu 26.04 LTS
sudo ln -sf /usr/bin/python3.13 /usr/bin/python3

Always match the symlink to your release’s default interpreter and invoke Python 3.12 explicitly using python3.12 rather than modifying the python3 symlink on production systems.

Virtual Environment Creation Fails

When python3.12 -m venv fails with an ensurepip error, the python3.12-venv package is missing.

The virtual environment was not created successfully because ensurepip is not available. On Debian/Ubuntu systems, you need to install the python3.12-venv package.

Install the missing package:

sudo apt install python3.12-venv

Verify that venv creation succeeds:

python3.12 -m venv ~/venvs/py312
source ~/venvs/py312/bin/activate
python --version
Python 3.12.12

Patch versions differ between Ubuntu 22.04 LTS and 24.04 LTS, so your output may show a different 3.12.x value.

For source-compiled installations, ensure you configured with --with-ensurepip=install before running make. If you skipped this flag, bootstrap pip manually using the get-pip.py script as described in the pip installation section.

GPG Signature Verification Fails

If signature verification fails with “No public key” or “Can’t check signature” errors, the release manager’s key was not imported correctly.

gpg: Can't check signature: No public key

Re-import the Python 3.12 release manager’s key:

curl -fsSL https://github.com/Yhg1s.gpg | gpg --import

If the key server is unreachable, you can fall back to SHA256 checksum verification. Compare your checksum output with the hash on the official downloads page:

sha256sum Python-*.tar.xz

Update or Remove Python 3.12

Update Python 3.12 Packages

sudo apt update
sudo apt install --only-upgrade python3.12 python3.12-venv python3.12-dev

Verify the updated version:

python3.12 --version
Python 3.12.12

Update Source Builds (Manual Script)

For source-compiled installations, use a dedicated update script to rebuild cleanly. Save the following script to your build directory:

cat <<'EOF' > ~/python3.12-build/update-python3.12.sh
#!/usr/bin/env bash
# Python 3.12 Source Update Script
# This script downloads and compiles the latest Python 3.12 release
set -euo pipefail  # Exit on any error, undefined variable, or pipe failure

# Check for required build tools
for cmd in curl tar make gcc; do
  if ! command -v "$cmd" > /dev/null 2>&1; then
    echo "Error: $cmd is required but not installed."
    echo "Run: sudo apt install build-essential curl"
    exit 1
  fi
done

BUILD_DIR="$HOME/python3.12-build"
PREFIX="/usr/local/python3.12"

# Confirm build directory exists
if [ ! -d "$BUILD_DIR" ]; then
  echo "Error: $BUILD_DIR does not exist."
  echo "Create it with: mkdir -p $BUILD_DIR"
  exit 1
fi

# Fetch the latest 3.12.x version number from python.org
echo "Checking for latest Python 3.12 version..."
PY312_VERSION="$(curl -s https://www.python.org/ftp/python/ | grep -oE '3\\.12\\.[0-9]+' | sort -V | tail -1)"
if [ -z "$PY312_VERSION" ]; then
  echo "Error: could not determine the latest Python 3.12 release."
  exit 1
fi
echo "Latest available: Python ${PY312_VERSION}"

# Display current version for comparison
echo "Currently installed:"
python3.12 --version 2>/dev/null || echo "Python 3.12 not found"
echo ""

# Download and extract source
cd "$BUILD_DIR"
rm -rf "Python-${PY312_VERSION}"
echo "Downloading Python ${PY312_VERSION}..."
curl -fsSLO "https://www.python.org/ftp/python/${PY312_VERSION}/Python-${PY312_VERSION}.tar.xz"
echo "Extracting source..."
tar -xf "Python-${PY312_VERSION}.tar.xz"
cd "Python-${PY312_VERSION}"

# Configure, compile, and install
echo "Configuring build (this takes a few minutes)..."
./configure --enable-optimizations --with-lto --with-ensurepip=install --prefix="$PREFIX"
echo "Compiling Python (5-15 minutes depending on hardware)..."
make -j"$(nproc)"
echo "Installing (requires sudo)..."
sudo make altinstall
sudo ln -sf "$PREFIX/bin/python3.12" /usr/local/bin/python3.12
sudo ldconfig

echo ""
echo "Update complete!"
python3.12 --version
EOF
chmod +x ~/python3.12-build/update-python3.12.sh

Run the script when you want to update to the latest 3.12.x release:

~/python3.12-build/update-python3.12.sh

Expected output when the update succeeds:

Checking for latest Python 3.12 version...
Latest available: Python 3.12.12
Currently installed:
Python 3.12.11

Downloading Python 3.12.12...
Extracting source...
Configuring build (this takes a few minutes)...
Compiling Python (5-15 minutes depending on hardware)...
Installing (requires sudo)...

Update complete!
Python 3.12.12

Avoid automating source builds with cron. Compilation can fail due to missing dependencies or network issues, so run the script manually and review the output each time.

Remove Python 3.12 Packages

Python 3.12 is the system interpreter on Ubuntu 24.04 LTS. Removing python3.12 will break apt, software-properties-common, cloud-init, and essential system utilities. Never run the uninstall commands below on Ubuntu 24.04 LTS. This section applies only to Ubuntu 22.04 LTS users who installed Python 3.12 via Deadsnakes PPA or users who compiled from source on Ubuntu 26.04 LTS.

For Ubuntu 22.04 LTS users who installed Python 3.12 via Deadsnakes PPA and no longer need it, uninstall the packages:

sudo apt remove --purge python3.12 python3.12-venv python3.12-dev
sudo apt autoremove

This command is safe on Ubuntu 22.04 LTS because the system interpreter remains Python 3.10. Verify your Ubuntu version before proceeding:

lsb_release -rs
22.04

Remove the Deadsnakes PPA

Additionally, remove the Deadsnakes PPA if your system no longer requires Python 3.12 packages:

sudo add-apt-repository --remove ppa:deadsnakes/ppa -y
sudo apt update

Clean Up Source-Compiled Installations

For source-compiled installations, delete the installation directory, symlink, and ld.so entry.

The following commands permanently delete the source-compiled Python 3.12 installation and the build directory. Back up the installation first if you want to keep locally installed modules, for example: cp -a /usr/local/python3.12 ~/python3.12-backup.

sudo rm -rf /usr/local/python3.12
sudo rm -f /usr/local/bin/python3.12
sudo rm -f /etc/ld.so.conf.d/python3.12.conf
rm -rf ~/python3.12-build
sudo ldconfig

If you used a custom prefix like --prefix=/opt/python3.12, remove that directory instead:

sudo rm -rf /opt/python3.12
sudo ldconfig

Conclusion

Python 3.12 delivers a stable runtime with security support through October 2028 and modern language features for new and existing projects. Ubuntu 24.04 LTS installs it from official repositories, Ubuntu 22.04 LTS uses the Deadsnakes PPA, and Ubuntu 26.04 LTS requires a source build. You now have verification steps, pip workflows, and troubleshooting guidance to keep Python 3.12 running without touching Ubuntu’s system interpreter.

Useful Links

Here are some valuable links related to using Python 3.12 on an Ubuntu system:

  • Python Official Website: Visit the official Python website for information about the programming language, its features, and download options.
  • Python Documentation: Access comprehensive documentation for detailed guides on installing, configuring, and using Python.
  • PEP 693: Python 3.12 Release Schedule: Review the official release schedule and security support timeline through October 2028.
  • What’s New in Python 3.12: Explore new features, deprecations, and improvements in Python 3.12.
  • Deadsnakes PPA: Access the community-maintained repository for Python versions not yet in Ubuntu’s official repositories.

2 thoughts on “How to Install Python 3.12 on Ubuntu”

    • Thanks for sharing this, Pasha. Python 3.12 isn’t available in Ubuntu’s universe repository for 22.04 LTS or 20.04 LTS – only Ubuntu 24.04 LTS ships it by default in the main repository. For Ubuntu 22.04 LTS, you’ll need the Deadsnakes PPA instead:

      sudo add-apt-repository ppa:deadsnakes/ppa -y
      sudo apt update
      sudo apt install python3.12 python3.12-venv python3.12-dev

      The guide now covers this installation method in detail under the “Install Python 3.12 via Deadsnakes PPA” section. You can verify package availability for different Ubuntu versions at packages.ubuntu.com.

      Reply

Leave a Comment