Jump to ratings and reviews
Rate this book

Clean Code in Python: Refactor your legacy code base

Rate this book
Getting the most out of Python to improve your codebase Python is currently used in many different areas such as software construction, systems administration, and data processing. In all of these areas, experienced professionals can find examples of inefficiency, problems, and other perils, as a result of bad code. After reading this book, readers will understand these problems, and more importantly, how to correct them. The book begins by describing the basic elements of writing clean code and how it plays an important role in Python programming. You will learn about writing efficient and readable code using the Python standard library and best practices for software design. You will learn to implement the SOLID principles in Python and use decorators to improve your code. The book delves more deeply into object oriented programming in Python and shows you how to use objects with descriptors and generators. It will also show you the design principles of software testing and how to resolve software problems by implementing design patterns in your code. In the final chapter we break down a monolithic application to a microservice one, starting from the code as the basis for a solid platform. By the end of the book, you will be proficient in applying industry approved coding practices to design clean, sustainable and readable Python code. This book will appeal to team leads, software architects and senior software engineers who would like to work on their legacy systems to save cost and improve efficiency. A strong understanding of Programming is assumed.

332 pages, Paperback

Published August 29, 2018

101 people are currently reading
372 people want to read

About the author

Mariano Anaya

2 books11 followers

Ratings & Reviews

What do you think?
Rate this book

Friends & Following

Create a free account to discover what your friends think of this book!

Community Reviews

5 stars
44 (34%)
4 stars
58 (45%)
3 stars
22 (17%)
2 stars
4 (3%)
1 star
0 (0%)
Displaying 1 - 13 of 13 reviews
Profile Image for Andrew.
43 reviews
January 10, 2019
A quite good introduction to "Clean" coding principals for the uninitiated, and a good tour of how these principals can be applied to create idomatic Python code.

I would have liked to see a little more treatment of asynchronous programming and how clean code applies to it.
Profile Image for Jon Ureña.
Author 3 books124 followers
December 1, 2018
For those who have been developing with Python for a while and want to delve deeper. After going through creating Pythonic code using magic methods, iterables, context managers, generators, etc., the book teaches the principles of clean code that will be familiar for those who have already read other books on code quality: design by contract, defensive programming, separation of concerns, composition versus inheritance, the SOLID principle, etc.

It goes into unit testing and design patterns as well. There is a lack of books about the latter adapted to Python, partly because the language integrates some of them or makes them redundant (such as the iterator and strategy patterns), given that in Python functions and classes are first class objects. Design patterns are always great to read about.

But it surprised me with a couple of things I didn't even know existed, such as descriptors (isolated class attributes) and a hardcore testing library that mutates operators in your functions, so you can truly make sure that those functions will handle change well. The last chapter also touches on isolating parts of the architecture into packages and containers, even using Docker; it clarified some aspects about an area that I find very irritating.
Profile Image for Anetti Lakusha.
2 reviews
February 6, 2023
This book is great to improve OOP skills in Python. It gives you a view about what can be done in Python and good practices to follow when programming in Python. Also, the way the author involve while you are reading the book is very good and the pieces fit together nicely. My concern about the book is the lack of examples, don't get me wrong, the book has a good level of code, but I think that examples should be more didactic. Some of them, I needed to read and re-read several times to understand and get the idea.
Anyway, is a great book and I really recommend it.
Profile Image for Vinicius.
151 reviews2 followers
October 24, 2020
Great book with plenty of examples about how to use Python in a clean way, a perfect complement to Clean Code and Clean Architecture books, by Robert Martin.
A must-read book to anyone craving for a better way to express himself through python code, with more concern about maintenance and code quality.
Profile Image for JamesDove322 Doves.
7 reviews
February 6, 2023
A must read for anyone who writes code for a living! I was pleased that many of the points in this book overlapped with what I follow in my day-to-day work, but I learned. I can say from my own experience that it is a difficult path, but if you don't want to learn, you can use the services of https://evnedev.com/services/ecommerce-software-development/ As for the book, this will be a reference book that I will share with my teams and colleagues without reservation!
Profile Image for Abbas.
17 reviews24 followers
April 11, 2022
A great book that goes beyond clean code and ventures into teaching you how to write more pythonic code as well.
Profile Image for Serhii Kushchenko.
110 reviews19 followers
October 26, 2022
This book disappointed me. It has an attractive table of contents, although poor quality of the content. It often happens with books. I regard it as a violation of ethics by the author and publisher.

A book on clean code in Python would do well to cover the topic of annotations in detail. However, in the book by Mariano Anaya, the annotations are mentioned only briefly.

Also, a substantial drawback of the book is that the author's style is immensely confusing. The sentences are long and intricate, and the examples are too few.

Instead of this book, I suggest you first study the book "Robust Python" by Patrick Viafore. It's more pleasant to read, and you'll get a lot more benefits out of it.

The book "Clean Code in Python" has several good chapters, so it is still worth having in your library, despite its significant shortcomings.

The chapters on SOLID principles and design patterns are good. They contain many practical examples. This book can also teach you how to write decorators, including advanced ones. One more good chapter is devoted to Python descriptors.
Profile Image for Gustavo Juantorena.
35 reviews3 followers
August 13, 2022
Nota: Leí la segunda edición de este libro.

Se trata de un libro técnico que viene a ayudar en varios puntos:

✅ Por un lado, cómo su nombre lo indica, propone consejos para escribir código más limpio, definiendo "código limpio" en función de su utilidad y aceptando que es un concepto sobre el que hay discusión.
En esta dirección nos propone buenas prácticas en varios aspectos: Nombres de variables, orden a nivel de código y a nivel arquitectura, principios SOLID, dependency injection, entre otros.

✅ A su vez, explica conceptos intermedios y avanzados de Python en profundidad (decoradores, corutinas, context managers, programación asíncrona, programación orientada a objetos) y precisa formas "Pythonicas" de resolver distintos problemas (con muy buenos ejemplos)

Algunos conceptos de valor que me llevo del libro (sin un orden en particular):

💡 Un buen código siempre tiene consistencia interna.

💡Documentar código no es lo mismo que escribir comentarios en él.

💡Nunca usar los comentarios para dejar una parte del código que ya no se va a usar. Si no se usa, se elimina.

💡Los Docstrings son documentación pero requieren mantenimiento regular. Si la función es chica y autoexplicativa, mejor no usarlos.

💡Todos los patrones de diseño no tienen por qué tener sentido en cualquier lenguaje.

💡Todos los métodos y atributos de un objeto son públicos.

💡No usar objectos mutables cómo argumentos default en las funciones. Da lugar a comportamientos inesperados.

💡 Cohesión significa que los objetos tiene que tener un propósito bien definido y ser lo más pequeño posible. Mientras que "coupling" se refiere a la interdependencia entre dos o más objetos. Queremos aumentar la cohesión y disminuir el coupling.

💡Generar software mantenible no significa preveer todo lo que pueda necesitarse en el futuro, sino que haga lo que se espera ahora y posea la flexibilidad suficiente para poder adaptarse a esa futuros requerimientos con facilidad.
Profile Image for Andrei Tarutin.
41 reviews2 followers
October 25, 2024
I am not a professional Python developer and my expertise mostly comes from .NET, however it was even more useful and interesting to read this book. I see how the technical details are different in Python and c# but the core software design principles are the same. In the end it doesn’t matter a lot which language you are writing in. You need to know the foundation and this books helps you to understand it.
Profile Image for Nickolai.
893 reviews8 followers
March 21, 2024
Отличная книга! Рекомендовал бы ее для обязательного изучения всем программистам среднего и продвинутого уровня. Для себя, поставил ее на второе место после Лутца.
Profile Image for Hiep Pham.
57 reviews36 followers
April 10, 2024
The sample codes are quite abstract. It would be better if the codes are put in a real context or a program to see how the ideas fit together.
Profile Image for Seburath.
154 reviews18 followers
July 1, 2021
Awesome book for beginners, full of examples!

Reading the summaries a couple of times to get context could be a good idea, before going deeper into every chapter.

The best is the information about the setup of a project and the design patterns comparison for python with the book written by the Gang of Four!

I never understood why "yield" is used on generators and asynchronous programming until now.

Despite I don't write all the examples of the book, I think is a good practice to do it, at least in the ones that are complicated to understand.
Displaying 1 - 13 of 13 reviews

Can't find what you're looking for?

Get help and learn more about the design.