DEV Community

loading...

Discussion on: How To Write Clean Code in Python

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
hanpari profile image
Pavel Morava

Python has no limit, only PEP8 prescribes the limit for the length of a line.

Unless you are a contributor to a standard library, you don't need to follow PEP8 at all.

Black, the Python's formatter, comes with 100 characters per line if I am not mistaken.

Personally, I prefer even shorter lines, but I am too lazy to mess with Black, so I keep its default setting.

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
jerrynsh profile image
Jerry Ng Author

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.

Thread Thread
hanpari profile image
Pavel Morava • Edited

Well, Python helps you split the line in the following fashion:


long_line = (
    "This is a very very very "
    "very very very very very very very "
    "very very very very very very very "
    "very very very very very long line."
    )

print(long_line)

>>> print(long_line)
This is a very very very very very very very very very very very very very very very very very very very very very very long line.

Enter fullscreen mode Exit fullscreen mode

Not sure how often you need long string lines, but you can split a string like this.
Despite more laborious, the result seems more readable to me.

Thread Thread
victorsgb profile image
victorsgb

This is quite useful! Thanks for sharing!

Thread Thread
hanpari profile image
Pavel Morava

You are welcome. By the way, note there is no concatenating operator between lines. The main difference between this and triple quotes strings is that there is no end of line character introduced unless typed explicitly.

Thread Thread
jerrynsh profile image
Jerry Ng Author

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

Thread Thread
hanpari profile image
Pavel Morava

Glad it is useful. I've collected plenty of little tricks and tips over the time, and I keep forgetting them regularly.

Whoever reads this and have a question, ask and I may perhaps recall another one 😀