Skip to content

The Python Environment#

Before you run solutions locally or in a take-home, you need a working Python setup — interpreter, virtual environment, package manager, and execution model. This page covers installation, running code, dependency management, testing, debugging, and the import system at a practical depth.

How to use this page

Set up once, then revisit when a project needs dependencies or a specific Python version. Pair with Basic Built-in Functions and Libraries.

At a glance
Track Python Basics
Sections 14 major topics
Outline Use the right-hand TOC to jump

Topics: Python implementations · Installing and selecting versions · How Python runs your code · Running code — all modes · Virtual environments — why and how · pip and dependency management · Project layout patterns · Testing · … (+6 more)

  1. Python implementations
  2. Installing and selecting versions
  3. How Python runs your code
  4. Running code — all modes
  5. Virtual environments — why and how
  6. pip and dependency management
  7. Project layout patterns
  8. Testing
  9. Debugging
  10. Environment variables
  11. Import system and PYTHONPATH
  12. IDE and tooling … and 2 more sections

Python implementations#

Implementation Notes
CPython Default from python.org — what 99% of interviews assume
PyPy JIT — faster loops, different C extension compatibility
Jython / IronPython JVM / .NET — rare
MicroPython Embedded — not interview relevant

Unless specified, "Python" means CPython.


Installing and selecting versions#

Source Use when
python.org Official installers (Windows/macOS)
Homebrew (brew install python@3.12) macOS developers
pyenv Multiple versions side by side
System Python (/usr/bin/python3) Avoid for projects — OS may depend on it
python3 --version
which python3
python3 -c "import sys; print(sys.executable, sys.version)"

pyenv workflow#

pyenv install 3.12.4
pyenv local 3.12.4      # .python-version in project dir
pyenv global 3.12.4

Use Python 3.10+ for match, | union types, better tracebacks. Confirm platform version on Codility/HackerRank before using 3.10-only syntax.


How Python runs your code#

Source (.py) → Parser → AST → Compiler → Bytecode (.pyc) → PVM executes
Mode __name__ value
Run file directly "__main__"
Imported as module module name ("mypackage.utils")
def solve():
    print("running")

if __name__ == "__main__":
    solve()   # only when executed directly

Bytecode cached in __pycache__/ — safe to delete.


Running code — all modes#

python3 script.py                 # run file
python3 -m package.module         # run as module (sets sys.path correctly)
python3 -c "print(2 + 2)"         # one-liner
python3 -i script.py              # run then interactive REPL
python3 -O script.py              # optimized — disables assert
python3 -X dev script.py          # development mode — extra runtime checks
python3 -m pdb script.py          # debugger
python3 -m profile script.py      # profiling
python3 -m timeit "code snippet"  # micro-benchmark

REPL tips#

>>> import this        # Zen of Python
>>> help(str.split)
>>> dir([])            # list attributes
>>> type(x)
>>> _                  # last result

IPython (enhanced REPL): pip install ipython%timeit, tab completion, magic commands.


Virtual environments — why and how#

Isolate project dependencies from system Python and other projects.

python3 -m venv .venv

# Activate
source .venv/bin/activate       # macOS/Linux
# .venv\Scripts\activate        # Windows cmd
# .venv\Scripts\Activate.ps1    # Windows PowerShell

# Verify
which python    # should point inside .venv
pip --version

deactivate
Without venv With venv
Package conflicts across projects Isolated site-packages
May need sudo for pip install User-writable
"Works on my machine" Reproducible via requirements

Alternative tools#

Tool Notes
venv stdlib — sufficient for most work
virtualenv Third-party, faster, more features
conda Data science stacks, non-Python deps
uv / pipx Modern fast tooling

pip and dependency management#

pip install requests
pip install "pandas>=2.0,<3"
pip install -r requirements.txt
pip freeze > requirements.txt
pip list
pip show numpy
pip uninstall requests
python3 -m pip install --upgrade pip

Dependency file formats#

File Purpose
requirements.txt Simple pinned list
requirements-dev.txt Test/lint deps
pyproject.toml Modern metadata (PEP 621), build system
Pipfile / Pipfile.lock pipenv
poetry.lock Poetry

Example requirements.txt:

pytest==8.2.0
black==24.4.2

Example minimal pyproject.toml:

[project]
name = "my-solution"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = []

For interviews: confirm whether third-party imports (NumPy, etc.) are allowed.


Project layout patterns#

Minimal script project#

my_project/
├── .venv/
├── solution.py
├── tests/
│   └── test_solution.py
├── requirements.txt
└── README.md

Package layout#

my_project/
├── .venv/
├── pyproject.toml
├── src/
│   └── mypackage/
│       ├── __init__.py
│       ├── core.py
│       └── utils.py
└── tests/
    └── test_core.py

Run package module: python3 -m mypackage.core from src/ parent with PYTHONPATH=src.


Testing#

pip install pytest
pytest
pytest tests/test_solution.py -v
pytest -k "edge"              # name filter
pytest --tb=short             # shorter tracebacks
pytest -x                      # stop on first failure
# tests/test_two_sum.py
from solution import two_sum

def test_basic():
    assert two_sum([2, 7, 11, 15], 9) == [0, 1]

def test_no_solution():
    assert two_sum([1, 2], 5) == []

def test_empty():
    assert two_sum([], 0) == []

unittest (stdlib)#

import unittest
from solution import two_sum

class TestTwoSum(unittest.TestCase):
    def test_basic(self):
        self.assertEqual(two_sum([2, 7, 11, 15], 9), [0, 1])

if __name__ == "__main__":
    unittest.main()

Run: python3 -m unittest discover.


Debugging#

python3 -m pdb script.py

Common pdb commands: n (next), s (step into), c (continue), l (list), p expr (print), q (quit).

IDE debuggers (VS Code/Cursor, PyCharm) provide breakpoints and variable inspection — use for take-homes.

# Quick debug print (remove before submit)
import pprint; pprint.pp(large_object)

# breakpoint() built-in (3.7+) — drops into pdb
breakpoint()

Environment variables#

import os

os.environ["API_KEY"] = "secret"          # set (child processes inherit)
api_key = os.environ.get("API_KEY")       # None if missing
debug = os.getenv("DEBUG", "false")       # with default

# All env as dict
os.environ.copy()
export DEBUG=true
export PYTHONPATH=src
python3 app.py

.env files with python-dotenv — load at startup in projects, not needed for whiteboard interviews.


Import system and PYTHONPATH#

Python searches sys.path in order:

  1. Directory containing script (or current dir for -m)
  2. PYTHONPATH directories
  3. Standard library
  4. site-packages (including venv)
PYTHONPATH=src python3 -m mypackage.main
import sys
sys.path.insert(0, "/path/to/src")   # last resort — prefer proper layout

Common errors:

Error Cause
ModuleNotFoundError Wrong cwd, missing PYTHONPATH, package not installed
ImportError Circular import, missing submodule
AttributeError on import Name not defined in module

Details: Modules and Packages.


IDE and tooling#

Tool Role
Ruff Fast linter + formatter (replaces flake8/black for many)
Black Opinionated formatter
mypy / pyright Static type checking
isort Import sorting
pip install ruff
ruff check .
ruff format .

Recommended for take-homes — shows professionalism.


.gitignore essentials#

.venv/
__pycache__/
*.py[cod]
*.egg-info/
.pytest_cache/
.mypy_cache/
.ruff_cache/
.env
dist/
build/

Interview / platform checklist#

Before starting a timed assessment:

  1. Confirm Python version (3.8? 3.10? 3.11?)
  2. Confirm allowed imports (stdlib only? NumPy?)
  3. Know how to run tests if provided
  4. Know class Solution: template vs free function
  5. Have local venv mirroring constraints for practice

Interview traps (quick reference)#

Trap What goes wrong Safe approach
System vs venv Python Wrong packages which python3 after activate
python vs python3 Wrong version / missing Use explicit python3
Unpinned deps Reproducibility failures Pin in take-homes
Wrong cwd Import errors Run from project root or -m
Global pip install Breaks system Python Always venv
3.10 syntax on 3.8 judge SyntaxError Match platform version

Mental model checklist#

  1. What does activating a venv change about python and pip?
  2. Why run packages with python -m instead of a script path?
  3. What is the difference between pytest and unittest?
  4. When should you set PYTHONPATH?
  5. Why pin dependencies in take-home projects?

What's next#

Topic Page
Standard library Basic Built-in Functions and Libraries
Modules and packages Modules and Packages
Language fundamentals Python Language Fundamentals