Chapter 1

Setting Up Python on Mac & PC

Version: 1.0.0 Last Updated: 2024-12-19 Reading Time: ~30 minutes
0% Complete

Overview

Setting up a proper Python development environment is the foundation for building scalable applications. This chapter covers everything you need to get started with Python development on both macOS and Windows, including environment setup, essential tools, and best practices for project organization.

You'll learn how to install Python, set up virtual environments, configure your development tools, and establish a workflow that supports scalable application development. These skills are essential for any Python developer working on system design and full-stack applications.

What You'll Learn:

  • Python installation and configuration
  • Virtual environment management
  • Development tool setup
  • Project structure and organization
  • Package management with pip
  • IDE and editor configuration

Python Environment Setup Workflow

Python Development Environment Components

Component Purpose Installation Method Configuration Verification
Python Interpreter Core runtime environment Official installer, pyenv PATH environment variable python --version
Package Manager (pip) Install Python packages Included with Python pip.conf, requirements.txt pip --version
Virtual Environment Isolate project dependencies venv, virtualenv Activation scripts which python
Code Editor/IDE Development interface VS Code, PyCharm Extensions, themes Feature testing
Version Control Code management Git installer User config, SSH keys git --version

Python Environment Setup Process

graph TD A[Download Python] --> B[Install Python] B --> C[Verify Installation] C --> D[Install pip] D --> E[Create Virtual Environment] E --> F[Activate Environment] F --> G[Install Dependencies] G --> H[Configure IDE] H --> I[Set up Git] I --> J[Create Project Structure] J --> K[Install Development Tools] K --> L[Verify Setup] C --> M{Installation Success?} M -->|No| N[Troubleshoot] N --> B M -->|Yes| D L --> O{Setup Complete?} O -->|No| P[Fix Issues] P --> L O -->|Yes| Q[Start Development] style A fill:#e1f5fe style B fill:#f3e5f5 style C fill:#e8f5e8 style D fill:#fff3e0 style E fill:#fce4ec style F fill:#e0f2f1 style G fill:#f1f8e9 style H fill:#e8eaf6 style I fill:#fafafa style J fill:#fff8e1 style K fill:#f3e5f5 style L fill:#e8f5e8 style Q fill:#c8e6c9

Key Environment Variables & Configuration

PYTHONPATH
/usr/local/bin/python3:/usr/bin/python3

Specifies additional directories to search for Python modules. Controls module import behavior and package discovery.

Python PATH Documentation →
VIRTUAL_ENV
/path/to/venv

Points to the active virtual environment directory. Used by Python to identify the current virtual environment.

Virtual Environment Documentation →
PIP_CONFIG_FILE
~/.pip/pip.conf

Location of pip configuration file. Defines package sources, user settings, and installation preferences.

Pip Configuration →
PYTHONSTARTUP
~/.pythonrc

Path to Python startup file executed when Python starts. Used for custom initialization and imports.

Python Startup Documentation →
PYTHONUNBUFFERED
1

Forces stdout and stderr to be unbuffered. Essential for real-time logging in containerized environments.

Python Unbuffered Documentation →
PYTHONDONTWRITEBYTECODE
1

Prevents Python from writing .pyc files. Useful for development environments to avoid cache issues.

Python Bytecode Documentation →

Critical Configurations

Python Version

  • Python 3.12+ (latest stable)
  • pip package manager
  • venv module for virtual environments

Development Tools

  • Git for version control
  • VS Code or Cursor IDE
  • Terminal/Command Prompt

Essential Packages

  • Flask for web development
  • SQLAlchemy for database ORM
  • pytest for testing

Mac Setup

Installing Python on macOS

macOS comes with Python 2.7 pre-installed, but we need Python 3.x for modern development. Here's how to set it up properly:

Using Homebrew (Recommended)

# Install Homebrew if you don't have it
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Python 3.12
brew install python@3.12

# Verify installation
python3 --version
pip3 --version

Homebrew is the preferred package manager for macOS. It handles dependencies and updates automatically.

Configuring PATH

Ensure Python is in your PATH by adding it to your shell configuration:

For Zsh (macOS Catalina+)

# Add to ~/.zshrc
echo 'export PATH="/opt/homebrew/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/opt/homebrew/opt/python@3.12/bin:$PATH"' >> ~/.zshrc

# Reload configuration
source ~/.zshrc

Alternative: Official Python Installer

If you prefer not to use Homebrew, you can download the official installer from python.org:

Steps for Official Installer

  1. Visit python.org/downloads
  2. Download Python 3.12.x for macOS
  3. Run the installer package
  4. Check "Add Python to PATH" during installation
  5. Verify installation in Terminal

Windows Setup

Installing Python on Windows

Windows doesn't come with Python pre-installed, so we'll need to install it manually:

Using Official Installer

# After installation, verify in Command Prompt
python --version
pip --version

# If python command doesn't work, try:
py --version
py -m pip --version

The Windows installer includes pip and adds Python to your PATH automatically.

Windows Subsystem for Linux (WSL)

For a more Unix-like experience on Windows, consider using WSL:

Installing WSL

# Enable WSL feature
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

# Install Ubuntu from Microsoft Store
# Then in Ubuntu terminal:
sudo apt update
sudo apt install python3 python3-pip python3-venv

Using Chocolatey Package Manager

Chocolatey is a package manager for Windows that makes installation easier:

Installing with Chocolatey

# Install Chocolatey first (run as Administrator)
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

# Install Python
choco install python

# Verify installation
python --version

Virtual Environments

Virtual environments are crucial for isolating project dependencies and avoiding conflicts between different projects.

Creating and Using Virtual Environments

# Create a new virtual environment
python3 -m venv myproject

# Activate the virtual environment
# On macOS/Linux:
source myproject/bin/activate

# On Windows:
myproject\Scripts\activate

# Your prompt should change to show the environment name
(myproject) $

# Install packages in the virtual environment
pip install flask sqlalchemy

# Deactivate when done
deactivate

Virtual environments create isolated Python environments where you can install packages without affecting your system Python.

Managing Dependencies

Keep track of your project dependencies:

Requirements File

# Generate requirements.txt
pip freeze > requirements.txt

# Install from requirements.txt
pip install -r requirements.txt

Best Practices for Virtual Environments

  • Create one virtual environment per project
  • Always activate the environment before working
  • Keep requirements.txt updated
  • Don't commit virtual environment folders to Git
  • Use descriptive environment names

Essential Packages

These packages form the foundation of modern Python web development:

Core Development Packages

# Activate your virtual environment first
source myproject/bin/activate

# Web Framework
pip install flask

# Database ORM
pip install sqlalchemy flask-sqlalchemy

# HTTP requests
pip install requests

# Testing framework
pip install pytest

# Environment variables
pip install python-dotenv

# Database migrations
pip install flask-migrate

# User authentication
pip install flask-login

# Verify installations
pip list

Flask Ecosystem

  • Flask: Core web framework
  • Flask-SQLAlchemy: Database integration
  • Flask-Login: User authentication
  • Flask-Migrate: Database migrations

Development Tools

  • pytest: Testing framework
  • python-dotenv: Environment management
  • requests: HTTP client
  • black: Code formatting

Code Editors

VS Code (Visual Studio Code)

VS Code is a popular, free code editor with excellent Python support:

VS Code Setup

  1. Download and install VS Code from code.visualstudio.com
  2. Install the Python extension (Microsoft)
  3. Install the Python IntelliSense extension
  4. Configure your Python interpreter

Cursor (AI-Powered Editor)

Cursor is built on VS Code but includes AI assistance:

Cursor Features

  • AI code completion and generation
  • Built-in chat interface
  • Code explanation and documentation
  • Bug detection and fixes

PyCharm (Professional IDE)

PyCharm is a full-featured Python IDE with advanced features:

PyCharm Benefits

  • Advanced debugging tools
  • Database integration
  • Built-in testing tools
  • Refactoring support

Python Development Environment Setup Process

Environment Configuration Dataset

Component Version Installation Method Configuration File Status
Python 3.12.0 Homebrew/Installer ~/.zshrc ✅ Required
Virtual Environment venv Built-in requirements.txt ✅ Required
Flask 3.0.0 pip install app.py ✅ Required
SQLAlchemy 2.0.23 pip install models.py ✅ Required
pytest 7.4.3 pip install tests/ ✅ Required
VS Code/Cursor Latest Download settings.json ✅ Recommended

Development Environment Setup Flow

flowchart TD A[Start: System Check] --> B{OS Detection} B -->|macOS| C[Install Homebrew] B -->|Windows| D[Download Python Installer] B -->|Linux| E[Use Package Manager] C --> F[Install Python 3.12] D --> F E --> F F --> G[Verify Installation] G --> H{Installation Success?} H -->|No| I[Debug Installation] I --> F H -->|Yes| J[Configure PATH] J --> K[Create Project Directory] K --> L[Initialize Virtual Environment] L --> M[Activate Environment] M --> N[Install Core Packages] N --> O[Flask Installation] N --> P[SQLAlchemy Installation] N --> Q[pytest Installation] O --> R[Configure IDE] P --> R Q --> R R --> S[Create Basic Flask App] S --> T[Test Application] T --> U{App Working?} U -->|No| V[Debug Issues] V --> S U -->|Yes| W[Environment Ready!] style A fill:#e1f5fe style W fill:#c8e6c9 style H fill:#ffecb3 style U fill:#ffecb3

Environment Variables & Configuration

PATH Configuration
export PATH="/opt/homebrew/bin:$PATH"

Adds Homebrew binaries to system PATH for macOS

📖 Python macOS Guide
Python Version
python3 --version

Verifies Python 3.12+ installation

📖 Python Downloads
Virtual Environment
python3 -m venv myproject

Creates isolated Python environment

📖 venv Documentation
Package Installation
pip install flask sqlalchemy pytest

Installs core development packages

📖 pip Documentation
Flask Configuration
app.config['SECRET_KEY'] = 'your-secret-key'

Sets Flask application secret key

📖 Flask Configuration
Database URI
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'

Configures SQLAlchemy database connection

📖 Flask-SQLAlchemy Config

Hands-On Exercise: Your First Flask App

Building a Simple Flask Application

Beginner

Objective

Create a simple Flask web application to verify your Python setup and learn basic Flask concepts.

Steps

  1. Set up your development environment
  2. Create a new project directory
  3. Set up a virtual environment
  4. Install Flask
  5. Create a simple Flask application
  6. Run and test the application

Complete Implementation

# app.py
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def home():
    return jsonify({
        "message": "Hello, Python is working!",
        "status": "success",
        "framework": "Flask"
    })

@app.route('/health')
def health():
    return jsonify({
        "status": "healthy",
        "message": "Flask is running"
    })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)

Running the Application

# Create project directory
mkdir my-first-flask-app
cd my-first-flask-app

# Create virtual environment
python3 -m venv venv

# Activate virtual environment
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install Flask
pip install flask

# Create app.py with the code above
# Then run:
python app.py

Testing

Open your browser and visit:

  • http://localhost:5000/ - Main endpoint
  • http://localhost:5000/health - Health check

Key Takeaways

🐍

Python Installation

Always use Python 3.x for new projects. Use package managers like Homebrew (Mac) or Chocolatey (Windows) for easier installation and updates.

🔒

Virtual Environments

Use virtual environments for every project to isolate dependencies and avoid conflicts between different projects.

📦

Package Management

Keep requirements.txt updated and use pip for package management. Consider using pip-tools for more advanced dependency management.

⚙️

Development Tools

Choose a code editor that fits your workflow. VS Code and Cursor are excellent choices for Python development.

Next Steps

Preparation for Chapter 2

Before moving to the next chapter, practice:

  1. Create multiple virtual environments for different projects
  2. Install and test different packages
  3. Modify the Flask app to add new routes
  4. Experiment with different code editors
  5. Set up Git for version control

Cross-References

Conclusion

You now have a solid Python development environment set up on your machine. This foundation will serve you well as we move into more advanced topics like AI-assisted development, database design, and system architecture.

Remember: A well-configured environment saves time and prevents "it works on my machine" problems that can frustrate both you and your teammates.