29,99 €
In the rapidly evolving tech industry, software applications struggle to keep pace with changing business needs, leaving developers grappling with complex codebases that resist change, ultimately reducing productivity and increasing technical debt. Clean Architecture with Python offers a powerful approach to address these challenges. Drawing from his extensive experience architecting cloud-native systems, Sam Keen helps you transform complex architectural challenges into digestible, implementable solutions.
This book teaches essential principles for effective development, emphasizing the Pythonic implementation of Clean Architecture. Through practical examples, you'll learn how to create modular, loosely coupled systems that are easy to understand, modify, and extend. The book covers key concepts such as the Dependency Rule, separation of concerns, and domain modeling, all tailored for Python development.
By the end of this book, you'll be able to apply Clean Architecture principles effectively in your Python projects. Whether you're building new systems or managing existing ones, you'll have the skills to create more maintainable and adaptable applications. This approach will enhance your ability to respond to changing requirements, setting you up for long-term success in your development career.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 412
Veröffentlichungsjahr: 2025
Clean Architecture with Python
Implement scalable and maintainable applications using proven architectural principles
Sam Keen
Clean Architecture with Python
Copyright © 2025 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing or its dealers and distributors will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Portfolio Director: Kunal Chaudhari
Relationship Lead: Samriddhi Murarka
Project Manager: Ashwin Dinesh Kharwa
Content Engineer: Alexander Powell
Technical Editor: Seemanjay Ameriya
Copy Editor: Safis Editing
Indexer: Manju Arasan
Proofreader: Alexander Powell
Production Designer: Jyoti Kadam
Growth Lead: Sayantani Saha
First published: June 2025
Production reference: 1030625
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-83664-289-3
www.packtpub.com
To my loving wife, Jin, whose unwavering support, patience, and encouragement made this book possible. Your belief in me through countless weekends spent coding and writing has been my greatest source of strength.
– Sam Keen
Sam Keen is a software engineering leader with over 25 years of experience. He is a polyglot developer who’s leveraged Python in varied contexts, from small start-ups to industry giants including AWS, Lululemon, and Nike. His expertise spans cloud architecture, continuous delivery, and building scalable systems. At Lululemon, Sam pioneered the company’s first cloud-native application development team, setting standards for distributed cloud architecture within the company. Currently, Sam leverages Python to design and implement internal platform engineering solutions for AWS focusing on Clean Architecture principles and maintainable code. Sam resides in the US Pacific Northwest with his loving wife and two very spoiled cats.
I want to express my gratitude to the team at Packt for their guidance and support throughout the writing process. Special thanks to the editors and reviewers whose feedback was invaluable in refining the concepts presented in this book. I’m also grateful to the open source community whose tools and libraries make Python development such a joy. Finally, thank you to my family for their unwavering support during the long hours of writing and coding.
Aindrila Ghorai is a lead architect with over 17 years of experience in software development, specializing in PEGA technology, artificial intelligence, and healthcare solutions. She has driven strategic, enterprise-wide BPM initiatives and contributed to operational excellence through Agile-Scrum and iterative methodologies. Aindrila has authored several peer-reviewed papers and served as a judge for prestigious awards including the Globee Awards, NCWIT, and Technovation Girls. Passionate about innovation and mentorship, she is dedicated to delivering transformative, sustainable solutions by leveraging emerging technologies and best practices.
Preface
Who this book is for
What this book covers
To get the most out of this book
Get in touch
Part 1: Foundations of Clean Architecture in Python
Clean Architecture Essentials: Transforming Python Development
Technical requirements
Why Clean Architecture in Python: the benefits of balancing planning and agility
The complexity challenge in modern Python development
The agility imperative
Striking a balance: the planning–agility trade-off
The role of architecture in managing complexity
Preparing for Clean Architecture
What is Clean Architecture?
The onion architecture concept
Benefits of Clean Architecture
Clean Architecture in context
Clean Architecture and Python: a natural fit
Implementing Clean Architecture in Python
Practical example: a glimpse of Clean Architecture in a Python project
Python-specific considerations and potential pitfalls
Balancing Pythonic code with architectural principles
Scaling Clean Architecture in Python projects
Leveraging Python’s dynamic nature appropriately
Testing considerations
Summary
Further reading
SOLID Foundations: Building Robust Python Applications
Technical requirements
Crafting focused, maintainable code: the power of single responsibility
Understanding single responsibility
SRP and testing
Balancing the SRP
Building extensible systems: embracing open–closed design in Python
ISP: tailoring interfaces to clients
From rigid to flexible: rethinking inheritance and interfaces in Python
Understanding LSP
The pitfalls of rigid hierarchies
Embracing flexibility with LSP
Decoupling for flexibility: inverting dependencies in Python
Understanding DIP
Fixing the design with DIP
DIP’s effect on testing
DIP in the context of SOLID and Clean Architecture
Summary
Further reading
Type-Enhanced Python: Strengthening Clean Architecture
Technical requirements
Understanding type awareness in Python’s dynamic environment
Evolution of typing in Python
Dynamic typing versus type hinting
Dynamic typing
Type hinting
Type awareness in Clean Architecture
Challenges and considerations
Leveraging Python’s typing system
Basic type hinting: from simple types to containers
Sequence: flexibility in collection types
Union and Optional types
Literal types
Type aliases
NewType
The Any type
Leveraging automated static type-checking tools
The mypy CLI
Configuring mypy
Mypy in deployment pipelines
Leveraging type hints in IDEs for improved development experience
Additional type-checking features
The Problems tab in VS Code
Git pre-commit hooks
Gradual adoption strategy
Summary
Further reading
Part 2: Implementing Clean Architecture in Python
Domain-Driven Design: Crafting the Core Business Logic
Technical requirements
Identifying and modeling the Domain layer using DDD
Understanding DDD
Analyzing business requirements
Core concepts of domain modeling
Modeling the task management domain
Task management application entities and value objects
Task management application domain services
Leveraging bounded contexts
Implementing entities in Python
Introduction to Python entities
Creating domain entities
Implementing the Task entity
Encapsulating business rules in entities
Distinguishing entity-level rules from domain-level rules
Value objects in Clean Architecture
Implementing domain services
Enhancing the domain model with aggregates and factories
DDD patterns
Aggregates
The factory pattern
Ensuring domain independence
The Dependency Rule in practice
Example 1
Example 2
Avoiding external dependencies
Domain layer independence and testability
Refactoring toward a purer domain model
Summary
Further reading
The Application Layer: Orchestrating Use Cases
Technical requirements
Understanding the role of the Application layer
Error handling with result types
Application layer patterns
Planning for evolution
Implementing use case interactors
Structuring a use case
Dependency injection
Handling complex operations
Defining request and response models
Request models
Response models
Maintaining separation from external services
Interface boundaries
Supporting evolving service requirements
Supporting optional integration
Adapting to service changes
Summary
Further reading
The Interface Adapters Layer: Controllers and Presenters
Technical requirements
Designing the Interface Adapters layer
Interface Adapters layer’s role in Clean Architecture
Responsibilities of the Interface Adapters layer
Interface Adapters layer versus Application layer boundaries
Key components and their relationships
Interface design principles
Implementing controllers in Python
Controller responsibilities and patterns
Working with request models in controllers
Maintaining controller independence
Enforcing boundaries through interface adapters
Explicit success/failure patterns at boundaries
Clean data transformation flows
Interface adapters and architectural boundaries
Building presenters for data formatting
Understanding the humble object pattern
Defining presenter interfaces
Working with view models
Implementing concrete presenters
Summary
Further reading
The Frameworks and Drivers Layer: External Interfaces
Technical requirements
Understanding the Frameworks and Drivers layer
Position in Clean Architecture
Frameworks versus drivers: understanding the distinction
Application composition
Clean Architecture patterns in the outer layer
Creating UI framework adapters
Framework adapters in practice
Component organization and boundaries
Implementing user interactions
Domain insights through implementation
Implementing domain insights: the task–project relationship
Implementing database adapters
Repository interface implementation
Managing repository instantiation
Component orchestration overview
Integrating external services
External services in Clean Architecture
SendGrid integration
Application bootstrapping
Summary
Further reading
Implementing Test Patterns with Clean Architecture
Technical requirements
Foundations of testing in Clean Architecture
Tests as architectural feedback
From testing complexity to clear boundaries
Testing clean components: unit testing in practice
Testing domain entities
Test double tools in Python
Testing use case orchestration
Testing interface adapters
Testing across architectural boundaries
Tools and patterns for test maintenance
Structuring test files
Parameterized testing for comprehensive coverage
Organizing test fixtures
Testing tools and techniques
Managing time in tests
Exposing state dependencies
Accelerating test execution
Summary
Further reading
Part 3: Applying Clean Architecture in Python
Adding Web UI: Clean Architecture’s Interface Flexibility
Technical requirements
Understanding interface flexibility in Clean Architecture
Understanding our web implementation
Parallel interface implementations
Common interface boundary violations
Web presentation patterns in Clean Architecture
Implementing web-specific presenters
Presenters versus template-based formatting
Managing web-specific state
Form handling and validation
Integrating Flask with Clean Architecture
Implementing routes and templates
Running your Clean Architecture web application
Summary
Further reading
Implementing Observability: Monitoring and Verification
Technical requirements
Understanding observability boundaries in Clean Architecture
Natural observation points in Clean Architecture
Understanding observability in Clean Architecture
Implementing cross-boundary instrumentation
Avoiding framework coupling in logging
Implementing structured logging patterns
Building cross-boundary observability
Verifying architectural integrity through fitness functions
Verifying layer structure
Enforcing dependency rules
Summary
Further reading
Legacy to Clean: Refactoring Python for Maintainability
Technical requirements
Evaluating and planning architectural transformation
Evaluating through a Clean Architecture lens
Conducting preliminary architectural analysis
Building stakeholder alignment
Deeper domain analysis
Creating a staged implementation roadmap
Approaches for doing the transformation work
Navigating the in-flight transformation
Progressive Clean Architecture implementation
Initial system analysis
Stage 1: establishing domain boundaries
Incremental integration strategies
Stage 2: Interface layer implementation
Identifying transformation boundaries
Implementing repository adapters
Building clean use cases
Implementing clean controllers
Stage 3: integration strategy: bridging legacy and clean implementations
Incremental transformation approach
Stage 4: optimization stage
Summary
Further reading
Your Clean Architecture Journey: Next Steps
Clean Architecture in retrospect: a holistic view
The journey through architectural layers
Python’s natural fit with Clean Architecture
Adapting Clean Architecture across system types
Clean Architecture in API systems
Framework considerations with FastAPI
Applying Clean Architecture with FastAPI
Event-driven architectures and Clean Architecture
Core concepts of event-driven architecture
Applying Clean Architecture for event-driven systems
Domain events as first-class citizens in Clean Architecture
Architectural leadership and community engagement
Leading architectural change
Building the case for Clean Architecture
Starting small: the power of exemplars
Overcoming resistance to architectural change
Balancing pragmatism and principle
Closing the implementation gap
Contributing Clean Architecture examples
Learning from multiple perspectives
Building your architecture community
Creating communities of practice
Summary
Further reading
Other Books You May Enjoy
Index
Cover
Index
Once you’ve read Clean Architecture with Python, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
This part establishes the fundamental principles and patterns of Clean Architecture in the Python context. You’ll gain a comprehensive understanding of the core architectural concepts, SOLID principles, and how Python’s type system can enhance your architectural implementations. These chapters provide the essential knowledge foundation upon which the rest of the book builds, setting you up for success in implementing Clean Architecture in your own Python projects.
This part of the book includes the following chapters:
Chapter 1, Clean Architecture Essentials: Transforming Python DevelopmentChapter 2, SOLID Foundations: Building Robust Python ApplicationsChapter 3, Type-Enhanced Python: Strengthening Clean Architecture