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)
Well written with excellant examples. This book will help you be a better python developer. Not for a complete beginner
Nice, practical guide to writing clean code in Python, that is, code that can be read and changed easily. The author points out that there are exceptions, that there are cases where the code doesn't need to be "clean". He provides a list of such cases. One example is "a simple script for a one-off task". This book is about the cases where "clean" is important.In the first chapter, it is emphasized that "If the code is not correct nor consistently structured, and everyone on the team is doing things in their own way, then we will end up with code that will require extra effort and concentration to be understood. It will be error-prone, misleading, and bugs or subtleties might slip through easily."I have experience working on a team that required good coding practices, and I think the above is a really good point. It's great to have team members who agree with that idea.The 10 chapters cover very interesting topics, and here are some of the features I like in each chapter:Ch 1) Intro, Code Formatting and Tools - mentions the importance of avoiding technical debt, recommends using tools to automate formatting and/or type checks such as mypy, pylint and black, and recommends following PEP-8.Ch 2) Pythonic Code - explains that "In programming, an idiom is a particular way of writing code in order to perform a specific task. It is the way things should be written when we want to perform a particular task. When the code follows these idioms, it is known as being idiomatic, which in Python is often referred to as Pythonic."In other words, Python code should be written in the Python way, and not as it would be written in, say, Java, or C++, and vice a versa, even though these approaches might be possible. Reasons given for this are that the code usually performs better, and the code can be more compact and easier to understand. Idiomatic features of Python are covered in detail, including example code snippets, such as: slices, context managers, and properties. It is recommended to not force code to be a one-liner, say in a comprehension, if that short code actually makes it much harder to read. Writing asynchronous code is introduced.Ch 3) General Traits of Good Code - explains Design by Contract and says, "the idea behind the DbC approach is that, instead of implicitly placing in the code what every party is expecting, both parties agree on a contract that, if violated, will raise an exception, clearly stating why it cannot continue." Also, describes Defensive Programming, which "follows a somewhat different approach to DbC. This is more about making all parts of the code (objects, functions, or methods) able to protect themselves against invalid inputs." Has nice discussion of error handling. Covers separation of concerns, cohesion, and coupling. Lists acronyms "to live by" - DRY/OAOO, YAGNI, KIS, EAFP/LBYL. Nice section on arguments in functions and methods. Also, good info on deciding between inheritance or composition, and avoiding common anti-patterns.Ch 4) The SOLID Principles - "key guidelines for good object-oriented software design". "The idea isn't to get all the requirements right from the very first version, but to achieve a design that's extensible and flexible enough to change, so that we can adapt it as needed." S = single responsibility principle, O = open/closed principle, L = Liskov's substition principle, I = interface segregation, D = dependency inversion. Not all code, or all parts of a system, should be written in an OO-way, just as an aside.Ch 5) Using Decorators to Improve Our Code - explains that decorators "can be applied to many things such as classes, methods, functions, generators, and many more". Describes when to use them: 1) "should be used when they are going to be applied multiple times (three or more times)" 2) "create cleaner interfaces, for instance, simplifying the definition of a class by extracting part of its logic into a decorator".Ch 6) Getting More Out of Our Objects with Descriptors - a more advanced feature in Python, descriptors are used internally in Python, but can also be used when writing code. The author suggests using descriptors for "truly generic cases, such as the design of internal development APIs, libraries, or frameworks".Ch 7) Generators, Iterators, and Asynchronous Programming - generators "make programs more efficient and iteration much simpler", and they support coroutines. Coroutines are generators, but they're semantically different.Ch 8) Unit Testing and Refactoring - unit testing is essential, and if they're easy to write, it suggests that the code is clear and well-designed. Covers the tools - unittest, pytest, and coverage, and Mock objects. Mentions property-based testing to address whether enough tests have been written and mutation testing as a way to test the tests. Discusses common themes in testing; i.e. boundary or limit values, classes of equivalence, and edge cases, and a little bit on Test-Driven Development, that is, writing tests before writing code. With TDD, code is written to implement functionality which is missing and causing the existing tests to fail.Ch 9) Common Design Patterns - DP's provide a way to communicate more effectively, as well as lead to clean design. "Thinking in terms of design patterns brings us closer to higher-level design." When thinking at this higher level, we can think about how the code will scale, change, and adapt. For a given pattern, there is analysis of how the final implementation is comparatively better by using the pattern than by not. The Gang of Four book is mentioned.Ch 10) Clean Architecture - the architecture needs to "express the intent of the problem it is trying to solve". Python packages are a way to reuse code, and cohesion and single responsibility principle are the "the most important considerations when deciding to create a package". Package implementation details are given. It is also shown how a microservice service "can be deployed in a Docker container starting from a packaged Python application".Regarding the principles presented in the book, the author finishes with "the best piece of advice the reader should take from the book—they are just principles, not laws", "practicality beats purity". The principles cannot always be fully achieved in terms of abstracting as much as one would like, or isolating dependencies.There are a lot of great topics here, a lot of good ideas to help write Clean Code in Python. This is a very nice book.
This is a useful book, especially as Python slowly becomes one of the dominant programming languages. Much of the information I have learned over the course of 15+ years of Python programming, so it's nice to see it in one place. And, to be honest, there were some back-end, low-level Python information that I didn't know.You'll find a lot of the information scattered around other books; there are some topics that I covered in my own books. But, again, for new Python programmers and those who spend most of their time using Python for data science, having a single source is good.The book starts with the fundamentals of good documentation and code formatting. Believe me, I've seen a lot of code that was obviously written by C/C++ programmers who were forced to write Python code for a one-off need, and it's not pretty.Chapter 2 talks about some of the "back-end" Python work. It's not totally low-level, e.g. how the underlying C code is used to make Python work, but does go into detail about some of the functionality of Python data structures.We then move into more information similar to Chapter 1: good code traits, SOLID principles, decorators, descriptors, testing, etc. While you can learn these over time if you hang out on programming forums, blogs, etc., the variety of opinions, especially from the anti-Python crowd, can make it hard to understand what is "Pythonic".Overall, this is a very valuable book for new Python programmers and those Python users who don't delve into general purpose programming. In addition, there is more detailed explanations for common Python "tools" that even long-time Python users might find useful, or at least interesting.
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