From Python 3.11 onward, Debian encourages the users to create a separate Python virtual environment to install Python packages.
Because Debian declares its Python install to be externally-managed, pip (and other installers) will refuse to install packages system-wide. Installation is only possible in virtual environments or separate Python installs.
This is because Python package installers (like pip) are unaware of the constraints that APT-managed packages have on libraries and versions. See PEP 668 for a full discussion of the problems that can occur when multiple installers operate on the same Python install.
Therefore, the optimal way is to create a virtual environment, say MyEnv, and install packages therein:
mkdir -p $HOME/.venvs # Create a folder for all virtual environments
python3 -m venv $HOME/.venvs/MyEnv # Create MyEnv
This will create a directory $HOME/.venvs/MyEnv with a configuration file pyvenv.cfg which includes some details for this virtual environment, such as the Python executable and Python version.
Verify the version of the Python in the virtual environment:
$HOME/.venvs/MyEnv/bin/python --version
The executables of the created virtual environment are found under $HOME/.venvs/MyEnv/bin.
To install a package into the virtual environment, use
$HOME/.venvs/MyEnv/bin/python -m pip install <some-package>
To 'activate' the virtual environment, i.e. adding its configuration variables into the shell environment, use
source $HOME/.venvs/MyEnv/bin/activate
Consult Python's guide to virtualenv and pip at Install packages in a virtual environment using pip and venv.
pipinstead ofpipxand check out how to utilize virtual environments.pipxis for installing applications, not libraries.