โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ
โ ๐ฏ Decorators | โก Generators | ๐ฎ Metaprogramming โ
โ โ
โ ๐งช Unit Testing | ๐จ Design Patterns | ๐ Best Practicesโ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Master the art of advanced Python programming with hands-on examples
- Overview
- Project Structure
- Topics Covered
- Environment Setup
- Installation
- Usage
- Learning Outcomes
- Resources
This repository contains a comprehensive collection of advanced Python programming techniques learned through hands-on practice and real-world applications. The project demonstrates mastery of Python's powerful features that separate intermediate developers from advanced practitioners.
- Functional Programming Paradigms - Leveraging decorators and higher-order functions
- Memory Optimization - Using generators for efficient data processing
- Dynamic Code Generation - Metaprogramming with metaclasses and the
type()function - Test-Driven Development - Building production-ready applications with comprehensive test coverage
Advanced-Python/
โ
โโโ ๐ README.md # This file
โโโ ๐ LICENSE # MIT License
โ
โโโ src/
โโโ ๐จ decorator/ # Decorator patterns and applications
โ โโโ decorator_timer_demo.py # Performance timing decorator
โ โโโ decorator_cache_demo.py # Memoization/caching decorator
โ โโโ decorator_logging_demo.py # Logging decorator
โ โโโ decorator_demo.md # Comprehensive decorator guide
โ โโโ test.py # Decorator tests
โ
โโโ โก generator/ # Generator functions
โ โโโ generator.py # Generator examples
โ
โโโ ๐ฎ metaprogramming/ # Metaclasses and dynamic programming
โ โโโ metaprogramming_demo.py # Dynamic class creation
โ
โโโ ๐งช unit_test/ # Test-Driven Development
โโโ demo/ # Flask blog application
โโโ app.py # Flask API endpoints
โโโ requirements.txt # Python dependencies
โโโ tests/ # Comprehensive test suite
โ โโโ conftest.py # pytest fixtures
โ โโโ test_app.py # Integration tests
โโโ templates/ # HTML templates
โโโ static/ # JavaScript and CSS
Decorators are one of Python's most powerful features, allowing you to modify or enhance functions without changing their code. This section explores practical decorator applications:
Measure function execution time for performance optimization:
@timer
def matrix_multiply(a, b):
return np.array(a) @ np.array(b)
# Output: Function matrix_multiply took 0.000123s to execute.Implement memoization to speed up expensive computations:
@cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)Automatically log function calls and arguments for debugging:
@log_function
def process_user_data(user_id, data):
# Processing logic here
passKey Concepts:
*argsand**kwargsfor flexible function signatures- Wrapper functions and closures
- Function metadata preservation with
functools.wraps - Practical applications in real-world projects
Generators enable memory-efficient iteration over large datasets by yielding items one at a time instead of loading everything into memory.
Benefits:
- ๐ Memory Efficient - Process large files without loading entire content
- โฑ๏ธ Lazy Evaluation - Compute values only when needed
- โพ๏ธ Infinite Sequences - Generate unlimited data streams
Use Cases:
- Processing large CSV files
- Reading log files line by line
- Creating data pipelines
- Implementing custom iterators
Metaprogramming is "code that writes code" - enabling dynamic class and function creation at runtime.
Create user classes dynamically based on runtime requirements:
def create_user_class(class_name, attributes):
"""Dynamically generates user classes with specified attributes."""
# Implementation uses type() to create classes on the fly
return type(class_name, (object,), class_attrs)
# Create different user types dynamically
BasicUser = create_user_class("BasicUser", ["username", "email"])
PremiumUser = create_user_class("PremiumUser", ["username", "email", "subscription_level"])Applications:
- ๐๏ธ Building flexible frameworks
- ๐ง Creating Domain-Specific Languages (DSLs)
- ๐ค Automating repetitive class definitions
- ๐ญ Implementing design patterns (Factory, Builder)
Key Concepts:
- The
type()function as a class factory - Metaclasses and
__new__method - Dynamic attribute assignment with
setattr - Runtime code generation
Built a complete Flask blog application using Test-Driven Development principles. This hands-on project demonstrates production-ready testing practices.
A full-stack web application built using TDD methodology:
Features:
- โ RESTful API with Flask
- โ Create and retrieve blog posts
- โ JSON data validation
- โ Comprehensive test coverage
- โ Beautiful responsive UI
- โ Error handling and status codes
Tech Stack:
- Backend: Flask 3.0.0
- Testing: pytest 7.4.3, pytest-mock
- Frontend: HTML5, CSS3, JavaScript (Fetch API)
The project includes 5 comprehensive integration tests:
- โ
test_posts_initialized_as_empty_list- Verify initial state - โ
test_get_posts- Test GET endpoint returns empty list - โ
test_create_post- Test successful post creation - โ
test_create_post_invalid_data- Test validation and error handling - โ
test_create_post_mock_posts- Test with mocked dependencies
GET / # Render home page
GET /posts # Get all blog posts (JSON)
POST /posts # Create new blog post (JSON)Example Request:
curl -X POST http://localhost:5000/posts \
-H "Content-Type: application/json" \
-d '{"title": "My First Post", "content": "Hello World!"}'Response:
{
"id": 1,
"title": "My First Post",
"content": "Hello World!"
}- ๐ด Red - Write failing tests first
- ๐ข Green - Write minimum code to pass tests
- ๐ต Refactor - Improve code while maintaining test coverage
Ensure you have the following installed:
- Python 3.10+ (Download)
- pip (Python package manager)
- virtualenv (recommended for isolated environments)
# Check Python version
python --version # Should be 3.10 or higher
# Verify pip installation
pip --versioncd ~/Documents
git clone <repository-url>
cd Advanced-Python-Development-Techniques/Advanced-PythonCreating a virtual environment keeps your project dependencies isolated:
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
# On macOS/Linux:
source venv/bin/activate
# On Windows:
venv\Scripts\activateYou should see (venv) prefix in your terminal.
Install required packages for different modules:
pip install numpycd src/unit_test/demo
pip install -r requirements.txtThis installs:
- Flask 3.0.0 - Web framework
- pytest 7.4.3 - Testing framework
- pytest-mock - Mocking utilities
- Werkzeug 3.0.1 - WSGI utility library
# Navigate to decorator directory
cd src/decorator
# Run timer decorator demo
python decorator_timer_demo.py
# Expected output:
# Function add took 0.000002s to execute.
# result1: 4998
# Function matrix_multiply took 0.000123s to execute.
# result2: [[19 22]
# [43 50]]
# Run cache decorator demo
python decorator_cache_demo.py
# Run logging decorator demo
python decorator_logging_demo.pycd src/generator
python generator.pycd src/metaprogramming
python metaprogramming_demo.py
# Output:
# Alice
# gold# Navigate to the project
cd src/unit_test/demo
# Run all tests with verbose output
pytest tests/ -v
# Expected output:
# tests/test_app.py::test_posts_initialized_as_empty_list PASSED
# tests/test_app.py::test_get_posts PASSED
# tests/test_app.py::test_create_post PASSED
# tests/test_app.py::test_create_post_invalid_data PASSED
# tests/test_app.py::test_create_post_mock_posts PASSED
# ========== 5 passed in 0.15s ==========
# Run specific test
pytest tests/test_app.py::test_create_post -v
# Run with coverage report
pip install pytest-cov
pytest tests/ --cov=app --cov-report=html# Make sure you're in the demo directory
cd src/unit_test/demo
# Start the Flask development server
python app.py
# Output:
# * Running on http://127.0.0.1:5000
# * Debug mode: onOpen your browser and navigate to: http://localhost:5000
# Create a new post
curl -X POST http://localhost:5000/posts \
-H "Content-Type: application/json" \
-d '{"title": "Advanced Python", "content": "Learning decorators!"}'
# Get all posts
curl http://localhost:5000/posts
# Test error handling (invalid data)
curl -X POST http://localhost:5000/posts \
-H "Content-Type: application/json" \
-d '{"title": "Missing content"}'By completing this project, I have gained expertise in:
- โ Understanding closures and higher-order functions
- โ Creating custom decorators for cross-cutting concerns
- โ
Using
*args,**kwargsfor flexible function signatures - โ
Preserving function metadata with
functools.wraps - โ Practical applications: timing, caching, logging, authentication
- โ Memory-efficient data processing
- โ Lazy evaluation and on-demand computation
- โ
Creating custom iterators with
yield - โ Generator expressions and comprehensions
- โ Use cases for large file processing
- โ
Dynamic class creation using
type() - โ
Understanding metaclasses and
__new__ - โ Runtime attribute manipulation
- โ Building flexible, adaptable frameworks
- โ Knowing when (and when not) to use metaprogramming
- โ Writing tests before implementation (Red-Green-Refactor)
- โ Using pytest for Python testing
- โ Creating fixtures and test configurations
- โ Integration testing for web applications
- โ Mocking dependencies for isolated testing
- โ Writing maintainable, well-tested code
- โ Building RESTful APIs with Flask
- โ Handling JSON requests and responses
- โ HTTP status codes and error handling
- โ Request validation and data sanitization
- โ Full-stack development (Backend + Frontend)
- Python Decorators ๐
- Python Generators โก
- Python Metaclasses ๐ฎ
- pytest Documentation ๐งช
- Flask Documentation ๐
- Fluent Python by Luciano Ramalho
- Python Cookbook by David Beazley
- Effective Python by Brett Slatkin
- Test-Driven Development with Python by Harry Percival
"Simple is better than complex. Complex is better than complicated."
โ The Zen of Python
- Decorators are powerful - They enable clean separation of concerns and code reusability
- Generators save memory - Essential for processing large datasets efficiently
- Metaprogramming is a superpower - Use responsibly to create elegant solutions
- Tests provide confidence - TDD ensures code quality and catches bugs early
- Python is expressive - Advanced features enable writing elegant, maintainable code
Feel free to explore, learn, and build upon this project! If you have suggestions or improvements:
- Fork the repository
- Create a feature branch
- Make your changes
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
Special thanks to:
- Coursera for the Advanced Python Development course
- Python Software Foundation for creating an amazing language
- The open-source community for continuous inspiration
๐ Happy Pythoning! ๐
Made with โค๏ธ and lots of โ
"Code is like humor. When you have to explain it, it's bad." โ Cory House