Skip to content

Default venv activate does not unset PYTHONPATH #136880

@glennglazer

Description

@glennglazer

Bug report

Bug description:

Working in Debian 12, if I create a venv and the shell I am in has a PYTHONPATH set to the system package directory, then this is preserved in the venv and import finds the wrong versions of things. In my specific case, it was finding the system django (3.2.19) instead of the venv django (5.2).

A proposed fix models after the PYTHONHOME code:

# in deactivate():
    if [ -n "${_OLD_VIRTUAL_PYTHONPATH:-}" ] ; then
        PYTHONPATH="${_OLD_VIRTUAL_PYTHONPATH:-}"
        export PYTHONPATH
        unset _OLD_VIRTUAL_PYTHONPATH
    fi

# in activate():
   if [ -n "${PYTHONPATH:-}" ] ; then
      _OLD_VIRTUAL_PYTHONPATH="${PYTHONPATH:-}"
      unset PYTHONPATH
   fi

This is all or nothing. If there is a use case somewhere that involves inheriting the PYTHONPATH to the shell, this would break that, but then I would argue that such inheritance violates the whole point of using a virtual environment.

CPython versions tested on:

3.11

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtopic-venvRelated to the venv moduletype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions