Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

Free eBook - Clean Code in Python - Second Edition

4.6 (34 reviews total)
By Mariano Anaya
  • A new free eBook every day on the latest in tech
  • 30 permanently free eBooks from our core tech library
  1. Introduction, Code Formatting, and Tools
About this book
Experienced professionals in every field face several instances of disorganization, poor readability, and testability due to unstructured code. This second edition has been updated to reflect new best practices in Python 3.9, helping developers write professional, scalable, and maintainable code. It introduces advanced object-oriented design, decorators, descriptors, and refactoring strategies using SOLID principles. Whether modernizing legacy projects or building new applications, this book provides practical techniques to write cleaner and more efficient Python code using the Python standard library and manage your projects successfully. The book begins by describing the basic elements of writing clean code and how it plays a key role in Python programming. The book discusses object-oriented programming in Python and show you the design principles of software testing and how to resolve problems by implementing software design patterns in your code. In the concluding chapter, we break down a monolithic application into a microservices-based one starting from the code as the basis for a solid platform. By the end of this clean code book, you will be proficient in applying industry-approved coding practices to design clean, sustainable, and readable real-world Python code.
Publication date:
January 2021
Publisher
Packt
Pages
422
ISBN
9781800560215

About the Author
  • Mariano Anaya

    Mariano Anaya is a software engineer who spends most of his time creating software with Python and mentoring fellow programmers. Mariano's principal areas of interest besides Python are software architecture, functional programming, distributed systems, and speaking at conferences. He was a speaker at Euro Python 2016 and 2017. To know more about him, you can refer to his GitHub account with the username rmariano. His speakerdeck username is rmariano.

    Browse publications by this author
Latest Reviews (34 reviews total)
This book is so comprehensible and exhaustive in its exposition of good coding practices in python, that in order to be fair to the author and to anyone reading this review, I thought it best to tackle it as a team. Thus, I employed the help of two of the brightest people I know, who also happen to be gifted engineers well-versed in the pythonic arts: Nikolay Avramov and Yoshi Carvajal. The paragraphs below is their combined take on the text.Ananya's treatise on clean code is an ambitious work. It attempts to convey the fundamental ideas which encapsulate (heh…) the art of writing maintainable, extensible software in Python, a language known for its simplicity, power, and unparalleled flexibility. Indeed, reminiscent of the 1970s Burger King "have it your way" ads, Python's elegant syntax, dynamic typing, and innumerable packages offers developers countless ways of writing and structuring software. Although one might be tempted to eat such a delicious syntactic burger whole, doing so comes with its own set of problems.With flexibility and dynamic typing come the perils of writing mangled, illegible spaghetti that would clog the arteries of any major codebase. Therefore, a Python developer is inadvertently forced to relinquish the engineering safeguards that come with other languages and must have the discipline and foresight to apply sound practices on his own.Such a badass developer must traverse this chaotic, desolate wasteland and comes face to face with a daunting question. How does one write Python code that others can understand and maintain while avoiding the pitfalls of a language that does not care too much about how things are accomplished?Before addressing the macro and micro scale code issues that a programmer might encounter, the author seems begrudging to provide an explicit definition for "clean code" -- something not unexpected for one of the more abstract topics in software engineering. Instead, he invites us to go through the book to form our own definition of what clean code means. This is brilliant strategy on Ananya's part; if he propped up an untenable or vague description too early on, then he'd consequently spend the remainder of the book defending that premature notion from all angles of attack and scrutiny. By admitting that clean code is inherently amorphous and situational he enables the reader to lower their defenses and embark on the journey together by situating himself not in the role of absolutist zealot, but rather, as a helpful tour guide pointing out significant landmarks in the clean code ecosystem that the reader may find beneficial. There is however no shortage to the number of such landmarks.Like the mythological hydra, this simple query embodies a complex, multi-faceted problem that necessitates a multi-pronged solution. This is, refreshingly, exactly the approach that the author opts for. Fundamentally, the strength of book comes from its willingness to address the general properties of well-engineered code along with the Python-specific details that go into writing it. This is extensively accomplished via the numerous examples that follow each corresponding concept.Ananya addresses macro scale code issues by explaining the engineering foundations that facilitate code legibility and re-use. Notable among these are lucid and enlightening explanations of principles such as coupling, cohesion, DRY, KISS, YAGNI, and SOLID. The sections on dependency inversion and design by contract, in particular, have had a deep impact on the way I look at writing re-usable and reliable code.The ideas of design by contract (DbC), cohesion, and the single responsibility principle (SRP) are especially pertinent when it comes to the matter of writing maintainable and thorough tests for our company's Python code base, a primary motivator for reading this book in the first place. Specifically, cohesion and SRP refer to designing components (classes, functions, entire packages) in such a way that the component in question is responsible for a single, well-defined purpose. Then, DbC comes into play via preconditions and postconditions, that is things that must hold true for the input to the component and the output of the component for us to consider said component as being functionally correct. These concepts synergize with one another when it comes to writing more testable code because the conditions will tell us whether the caller of the code is broken (invalid preconditions) or if the component itself is incorrect (invalid postconditions). Furthermore, we will know that when a behavior is not working as intended, which component is responsible for said behavior due to the one-to-one mapping of behavior to component guaranteed by SRP.These macro scale insights are coupled (heh…) with micro scale explanations which address numerous low-level topics. Any developer that desires a deeper look at Pythonic syntax and correct usage of the language's powerful features would find this book worth their while. Chapters that were particularly helpful were ones which covered more esoteric but elegant language features that I myself have not made proper use of until I read Ananya's work. To name but a few of these: magic methods, context managers, decorators, and extensions of basic types.A microscale section I specifically found useful is the interplay between defensive programming, exception handling, and assertion statements. This is a good example because while I have been aware of these topics separately for a long time, it wasn't until Ananya made his case on the matter that I realized readability can be enhanced by strictly delegating when to use exceptions and when to use assertions. So, it is not only a matter of Ananya introducing previously unseen syntactic devices – tremendous value also lies in when he shows you how to use something you've already seen many times before but in a new light that promotes cleaner coding practices. Similar arguments can be made for all of the esoteric language features aforementioned in the previous paragraph, along with proper star and double star operator usage.This brings me to what I consider the most effective feature of this book, which are the concrete examples that turn abstract, albeit clear, descriptions into a tangible reality. This is wonderful for me as a developer — when I look at documentation for a new library or some piece of code, the first things I look at are the code examples. The examples provided in Clean Code are wonderful and showcase the barebones concept they're trying to explain, free of any distractions that might lead a reader astray. There were a few times where the examples in the book were enough to get me to understand the concept, but left me with a desire to see further examples on Google. I don't know if this is a potential drawback of the book, but I thought it might be worth mentioning.A first runner up are the complete and cohesive (heh heh…) summary sections one can locate at the end of every chapter. They do an excellent job of summarizing the material touched upon throughout the chapter and they tie that material back into the broader concept of writing clean code. I personally found it useful to read through the summaries prior to engaging in the body of each chapter since they do a good job of showing you where that material fits in the big picture. I believe these end of chapter summaries could be enhanced with questions that enable the user to apply the concepts from the chapter. For example, provide the reader with an example of messy code, and have them clean up the code by implementing concepts from that chapter (a potential solution to each question can be listed in the back of the book for the sake of compactness). This would have made the material more interactive and hands on and is perhaps the only thing that I was expecting to see that was not included. But again, the bountiful examples used throughout the book ameliorate this deficit.There are many tools and techniques presented in the book which, if applied wisely, can make code a dream to work with. Thankfully, the author places emphasis on using the techniques in the book cautiously and with common sense. For example, I wasn't aware of the rule of thumb for creating reusable abstractions which should be based on, at minimum, three separate instances of the component in question. These tidbits of knowledge are useful, since when you've got a hammer, everything looks like a decorator or abstract base class.All of this said, this is a dense and information packed book that will take time to fully digest. In a way, I feel like I've jumped five years into the future, where things I would have discovered by basic trial and error have been revealed to me much sooner (although, many things that the book illuminates would be difficult to glean through simple trial and error)
I’m a long time C#, .NET developer and have read and absorbed and taken to heart Uncle Bob’s Clean Code and Clean Architecture books. Recently I’ve started learning Python and, with any programming language I learn, I like to also learn the best way to use that language and how to develop clean code and clean architectures with it.This is why I love Mariano Anaya’s second edition of “Clean Code in Python” book. It immediately meets both of my requirements here. But is not only a great book for Python newbies, like me, but experienced Python devs will definitely find a lot of value from it.Mariano does a great job explaining the what and the why of each topic. He wants you to understand the pros and cons of each approach. He explains each side of the argument, showing various alternatives, to help you understand the best approach and avoid common mistakes.I loved this quote from Mariano, “Practicality beats purity.” He gives you solid, practical, real-world examples and shows when to deviate from pure patterns sometimes – to be practical. He has great, long-term design thinking with considerations for future changes in mind, making your software flexible and extensible – the Pythonic way.He starts with simple examples to help you understand the concepts then moves on to more advanced topics, including describing how Python works under the covers.A takeaway summary:• Emphasizes the Pythonic way to code.• Best practices and traits of software design , anti-patterns, debugging tips.• Has an entire chapter on the SOLID principles. Also touches on these principles throughout the book.• Explains the power of decorators and descriptors, an advanced Python feature, to improve your code.• Covers generators, iterators, coroutines, and asynchronous programming.• Importance of unit testing. Shows how to make code more unit testable and that it is just as important as production code.• Describes the importance of refactoring and shows the importance of unit tests to make this work effectively.• Common design patterns and how they contribute to clean code. Design patterns considerations for Python since there are many patterns already inherently embedded in Python.• Great chapter on clean architectureHighly recommended!A few of my favorite quotes:“The ideas explored in this chapter are fundamental pillars in the global context of the book because of their importance to our ultimate goal: to write better and more maintainable software.”“The reason why we pay so much attention to the code's flexibility is that we know requirements change and evolve over time, and eventually, as domain business rules change, our code will have to change as well to support these new requirements.”“As introduced at the beginning, the goal of this book was not to give you recipes or formulas that you can apply directly, but rather to develop your critical thinking. Idioms and syntax features come and go; they change over time. But ideas and core software concepts remain. With these tools and the examples provided, you should have a better understanding of what clean code means.”
I learned a lot from this book. It'll be an invaluable reference going forward as well. Highly recommended.
Recommended For You
Expert Python Programming - Fourth Edition

Attain a deep understanding of building, maintaining, packaging, and shipping robust Python applications

By Michał Jaworski and 1 more
Python Data Cleaning Cookbook

Discover how to describe your data in detail, identify data issues, and find out how to solve them using commonly used techniques and tips and tricks

By Michael Walker
Data Engineering with Python

Build, monitor, and manage real-time data pipelines to create data engineering infrastructure efficiently using open-source Apache projects

By Paul Crickard
Mastering Python for Networking and Security - Second Edition

Tackle security and networking issues using Python libraries such as Nmap, requests, asyncio, and scapy

By José Manuel Ortega