Preparing your experience...

Quick Python venv Load — Local First, Then Global

— 2 min read

Switching between Python projects should be instant. The pattern below gives you that speed with a single command: check for a local .venv in the current directory, and fall back to a global ~/.venv if one doesn't exist.

Note: This guide covers macOS and Linux (bash / zsh). Windows uses Scripts\activate instead of bin/activate, and paths use \ rather than /. Adapt the function accordingly or run it in Git Bash / WSL where bash is available.

The function

Add this to your ~/.bashrc (or ~/.zshrc):

pyon() {
    if [ -f "./.venv/bin/activate" ]; then
        source "./.venv/bin/activate"
    elif [ -f "$HOME/.venv/bin/activate" ]; then
        source "$HOME/.venv/bin/activate"
    else
        echo "pyon: no venv found in ./.venv or ~/.venv" >&2
        return 1
    fi
}

Then reload your shell config with source ~/.bashrc and you're done.

How it works

Run pyon from any directory. The function checks two locations in order:

  1. Local: .venv/bin/activate — the project-specific virtual environment, created by python3 -m venv .venv.
  2. Global: ~/.venv/bin/activate — your personal catch-all environment for projects that don't ship their own venv.

If neither exists, it prints an error and exits with code 1 so you know immediately something is wrong.

Creating the global venv

For projects without a local virtual environment, set up a single global one once:

python3 -m venv ~/.venv

Then run pyon in any project directory — it will activate that shared environment automatically.

Gotcha: If you create a new local .venv inside a project that was previously using the global one, remember to run pyon again from within that project's directory. The function resolves at call time, not at shell startup.

Why this beats manual sourcing

The traditional approach is remembering and typing the full path each time:

source my-project/.venv/bin/activate

That breaks as soon as you change directories or work across multiple projects. With pyon, you type one word — regardless of where you are — and it finds the right environment for you. It also works in subdirectories, which is how most developers navigate their project folders anyway.

Deactivating

As with any virtual environment, exit with:

deactivate

This restores your shell to the system Python. The pyon function itself does not interfere with deactivate.

TenolifeTENOLIFE