conda environment has access to system modules, how to prevent?

In addition to what @VikashB mentioned, these can result from packages installed with pip install --user. As @TimRoberts alluded to in the comments, the site module, which populates the sys.path variable, searches paths like ~/.local/lib/python*/site-packages by default.

Temporary Options

One can disable the site module from loading such packages (see PEP 370), either by launching Python with an -s flag (python -s) or by setting the environment variable PYTHONNOUSERSITE:

export PYTHONNOUSERSITE=1
python

Longer-term options

Hiding from site module

If you need to keep these packages for some reason, one option is to move them to a non-default location so the site module doesn’t find them. For example,

mkdir ~/.local/lib/py_backup
mv ~/.local/lib/python* ~/.local/lib/py_backup

This will effectively hide them, and they could still be used through PYTHONPATH if necessary.

Removal

If you don’t need the packages, and only use Conda then consider just removing them

rm -r ~/.local/lib/python*

For reference, Conda users are discouraged from using the --user flag in the Conda documentation. Conda environments assume full isolation of environments, so leakage such as OP reports can lead to undefined behavior.

Experimental: envvar-pythonnousersite-true

In response to another question, I put together a simple Conda package that sets the PYTHONNOUSERSITE=1 variable at environment activation time. There are other ways to set environment variables, but this is a quick and minimal patch.

It can be installed with:

conda install merv::envvar-pythonnousersite-true

Leave a Comment