Image for post
Image for post
Source: https://twitter.com/codedoesmeme/status/1098869612161179649

How To Write Better Python Code?

Priyansi
Priyansi
May 19, 2020 · 6 min read

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 -

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 -

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

# 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.

Image for post
Image for post
Source: http://www.lpycot.appspot.com/archive/2001

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.”

Image for post
Image for post
Source: https://luminousmen.com/post/the-ultimate-python-style-guidelines

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 -

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-

# 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 -

# 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.

Image for post
Image for post

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-

names = 'ABC'
for combination in combinations(names, 2):
print(combination)
''' 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 -

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, val)
''' 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.

Image for post
Image for post
Source: https://me.me/i/you-public-class-helloworld-1-2-public-static-void-main-9282350

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 -

Image for post
Image for post
Source: https://imgur.com/t/home_alone/jXUUJK2
# good code
def is_positive(num):
return num >= 0
# while comparing None
# 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 there were my two cents on the most basic ones. DM me on Twitter if you agree with me, disagree, or just want to wish me a good day. Congratulations! You are now a Pythonista.

Mozilla_Club_Bbsr

Mozilla Club Bbsr is a community that puts people before profit and work in open-source environment.

Priyansi

Written by

Priyansi

Loves programming languages as well as natural ones

Mozilla_Club_Bbsr

Mozilla Club Bbsr works in contributing to the open-source and spread literacy in the field of web, app, languages like Rust and in emerging new technologies in all sectors of the society.

Priyansi

Written by

Priyansi

Loves programming languages as well as natural ones

Mozilla_Club_Bbsr

Mozilla Club Bbsr works in contributing to the open-source and spread literacy in the field of web, app, languages like Rust and in emerging new technologies in all sectors of the society.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store