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)
- 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
- Debugging
- Environment variables
- Import system and
PYTHONPATH - 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 |
pyenv workflow#
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#
| Mode | __name__ value |
|---|---|
| Run file directly | "__main__" |
| Imported as module | module name ("mypackage.utils") |
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:
Example minimal pyproject.toml:
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#
pytest (recommended)#
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#
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()
.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:
- Directory containing script (or current dir for
-m) PYTHONPATHdirectories- Standard library
- site-packages (including venv)
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 |
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:
- Confirm Python version (3.8? 3.10? 3.11?)
- Confirm allowed imports (stdlib only? NumPy?)
- Know how to run tests if provided
- Know
class Solution:template vs free function - 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#
- What does activating a venv change about
pythonandpip? - Why run packages with
python -minstead of a script path? - What is the difference between pytest and unittest?
- When should you set
PYTHONPATH? - 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 |