DEV Community

Cover image for How To Write Better Python Code?

How To Write Better Python Code?

iiverveii profile image Priyansi Originally published at Medium ・5 min read

Python Meme
We all love Python. It’s easy to write and understand but that doesn’t give us the right to abuse a wonderful language by ignoring the rules and writing code in a non-Pythonic way. Consider this article as the Zen of Python: Extended. Here are 10 ways to write better code in Python:

Are you writing C code?

If you were asked to print all the elements in a list along with their indexes and the first thing that came to your mind was this -

for i in range(len(arr)):  
    print(i, arr[i])

Then you, my friend, are still writing C code. Allow me to introduce you to enumerate. It indexes all the elements in your list/string and your code becomes -

for i, j in enumerate(arr):  
    print(i, j)

Well, now it looks better and more Pythonic. What about converting a list into a string?

# The C way  
string = ''  
for i in arr:  
    string += i

# The Python way  
string = ''.join(arr)

Just like join, Python has a plethora of magical keywords, so don’t work for the language, make the language work for you.

Alt Text

Remember PEP8?

It’s like the rulebook you probably throw away because you are one of the cool kids. I’m not asking you to religiously follow it, all I’m asking for is to follow most of it because our founding father said that “Code is read much more often than it is written,” and he was dang right.

Do you ever look at your code and wonder? What the heck does that do? Why is it there? Why do I exist? Well, PEP8 is the answer to most of these questions. While comments are a good way of explaining your code, you still need to change the code and if you can’t remember what i, j, count, etc stand for, you’re wasting your valuable time as well as of the poor human that’ll have to read and change your code.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

Alt Text

Prefer CamelCase for classes, UPPER_WITH_UNDERSCORES for constants, and lower_with_underscores for variables, methods, and module names. Avoid single name functions, even when using lambda. In the spirit of that, let’s change our previous code to -

for ind, val in enumerate(arr):  
    print(ind, val)

Are list comprehensions your best friend?

If you don’t know about it yet or aren't convinced why you should use it, let me give you an example-

# bad code  
positives = []  
for val in arr:  
    if val >= 0:  

# good code  
positives = [val for val in arr if val >= 0]

You can use this for dictionaries and sets. It’s even perfect for playing code golf while being readable.

Still explicitly closing files?

If you are a forgetful person like I am, Python has your back. Instead of explicitly opening your file and then typing filename.close() every time, simply use with -

with open('filename.txt', 'w') as filename:  
# when you come out of the 'with' block, the file is closed

Iterators or generators?

Both iterators and generators are powerful tools in Python that are worth mastering. An iterator returns an iterator object, one value at a time whereas generators yield a sequence of values while being memory efficient as they do not store the entire range of values, rather generate one only when you ask for it, unlike iterators that return the entire range of values. This makes generators extremely fast, compact, and simple.

To yield or not to yield?

When using generators, blindly use yield. It will freeze the state of the generator and resume again from where you left off, should you require another value. But don’t use it, just for the sake of not using return. Both have their place and it is neither fancy to use yield nor ordinary to use return.

Alt Text

Ever heard of itertools?

A faster, more memory-efficient way to perform iterator algebra. From count and cycle to groupby and product, this module has some amazing tools to make your life easier. If you want all the combinations of characters in a string or of numbers in a list you can simply write-

from itertools import combinations
names = 'ABC'  
for combination in combinations(names, 2):  
''' Output -  
    ('A', 'B')  
    ('A', 'C')  
    ('B', 'C')  

May I introduce you to Python’s collections?

The collections module provides alternatives to built-in data types like dict, tuple, etc. They have various containers like defaultdict, OrderedDict, namedtuple, Counter, deque, etc that work really efficiently for some problems. Allow me to demonstrate -

# frequency of all characters in a string in sorted order
from collections import (OrderedDict, Counter)
string = 'abcbcaaba'  
freq = Counter(string)  
freq_sorted = OrderedDict(freq.most_common())
for key, val in freq_sorted.items():  
    print(key, oval)
''' Output -  
    ('a', 4)  
    ('b', 3)  
    ('c', 2)  

Is OOP your religion?

Don’t overuse classes. Hang on Java and C++ peeps who are out there to get me. You can keep all your fancy classes and functions that are slaves to objects (yes Java, I’m looking at you), but when using Python you can just re-use code with the help of functions and modules. You don’t have to create classes when there is absolutely zilch need for it.

Alt Text

Docs or Tutorials?

You have truly progressed as a programmer when you prefer docs over tutorials or StackOverflow. I absolutely do not mean that documentation is the better being and tutorials shouldn't exist, however, once you are comfortable with a language, read docs more often, especially for something so beautiful like Python where everything is so perfectly explained that you could read it like a story-book. You will find interesting things to play around with and even if you don’t use them, it will be a fun ice-breaker at an all-coders party :p

Bonus code snippets for the lucky people who stayed till the end -

Alt Text

# bad code  
def is_positive(num):  
    if num >= 0:  
        return True  
        return False
# good code  
def is_positive(num):  
    return num >= 0

# bad code  
if value == None:  
    # some task
# good code  
if value is None:  
    # some task

# unpacking a list into a variable and another list  
roll, *marks = roll_and_marks

There are numerous other ways in which we can write more Pythonic code but these were my two cents on the most basic ones. Comment down below if you agree with me, disagree, or just want to wish me a good day. You can also reach out to me on Twitter. Congratulations! You are now a Pythonista.

Discussion (14)

thijs0x57 profile image

Very useful article, I just started using Python from a very heavy OOP background

iiverveii profile image
Priyansi Author

Good luck learning Python! May you become embrace your inner Pythonista.

muhammadaadil50 profile image

This is a vast topic.. It needs much concentrations more than explained.. Thanks.. I am shocked at some point even as Intermediate pythonic programmer.. I think you must create regular series beginning to advance pythonic coding.. It will be pleasure for us.. If possible it would be highly appreciated..

chrisgreening profile image
Chris Greening

Yessss really loved this article, everytime I learn a more pythonic way of doing something I feel the power surge through my bones. Likewise, every time I have to work in another language that doesn't have listcomp's or other syntax tricks that I've taken for granted I get very, very sad lol

djamaile profile image

You said no classes, but what would you recommend for repeating arguments? Currently I am using dataclasses for that.

iiverveii profile image
Priyansi Author

I never said 'no classes'. Obviously, they have their place like in your case. I said prefer functions over classes and group similar functions into modules rather than merely use a class for behavior grouping :)

djamaile profile image

Aha thanks, happy coding😉.

Thread Thread
iiverveii profile image
cereal84 profile image
Alessandro Pischedda

Nice article.

In list comprehensions example, on "bad code", is missing 'value' in append() method.

iiverveii profile image
Priyansi Author

Thank you for pointing that out! Fixed it :)

rodrigoghiraldeli profile image
Rodrigo Ghiraldeli

Thank you very much for this article! :D

iiverveii profile image
Priyansi Author

Thank you for taking the time to read it :)

sivakumarskr profile image
Sivakumar R

A good refresher article for me. Good one.

iiverveii profile image
Priyansi Author

Thank you :)

Forem Open with the Forem app