DEV Community

How To Write Clean Code in Python

Jerry Ng on July 14, 2021

What exactly is “clean code”? Generally speaking, clean code is code that is easy to understand and easy to change or maintain. As code is more of...
Collapse
 
naruaika profile image
Naufan Rusyda Faikar • Edited

Python "has" a maximum limit of 80 characters, even though I don't always agree. Often, it is a great challenge for me to choose between writing self-explanatory code (or someone call it as verbose naming) or following the consensus (which is all about the Python linter). But anyway, most of the time, I prefer the former to the latter. For the reason, then I started leaving the rule and expand it to 100 or 120.

Edit: I forgot to mention, it's hard to move on from being a big fan of one-liners. Ha-ha-ha ...

Collapse
 
zodman profile image
Andres 🐍 in 🇨🇦

insted of:

expiration_date = '2021-04-17 03:25:37.403283' # OR
expiration_date_string = '2021-04-17 03:25:37.403283'
Enter fullscreen mode Exit fullscreen mode

I suggest or its better

expiration_at = "2021 ..."
Enter fullscreen mode Exit fullscreen mode
Collapse
 
arvindpdmn profile image
Arvind Padmanabhan

Many beginners don't give importance to naming. They don't realize that many others will be reading and maintaining their code. More about naming conventions is at devopedia.org/naming-conventions

Collapse
 
jerrynsh profile image
Jerry Ng

I personally find it hard to adhere to the PEP8 max line length guideline at times especially when dealing with relatively long strings whether the line breaks could potentially look odd.

But then again this is a personal/team preference I suppose.

Collapse
 
daephx profile image
daephx

Iirc black's philosophy shies away from heavy configuration when compared to other formatters.

However they do provide a cli argument black --line-length 80 myfile.py

Collapse
 
ucavalcante profile image
Ulisses Cavalcante

Nice article, I'm not from python but i easily understood everything ty.

Collapse
 
albertolramos profile image
AlbertoLRamos

Trabaje mucho tiempo en C++ STD, en el equipo establecimos un Code Style en QtCreator, nos ayudó mucho. Tu trabajo está bueno, gracias

 
victorsgb profile image
victorsgb

This is quite useful! Thanks for sharing!

 
jerrynsh profile image
Jerry Ng

The code snippet that you provide is super helpful! Thanks for sharing it!