3 Steps to Coding Pythonic
Pythonic comes from Idiomatic.
Idiomatic means something that can’t be translated one-to-one but everyone understands what it means, like “hit the books” means “study hard”. The one-to-one translation is not enough to understand that phrase, you have to understand it with some prior knowledge.
Pythonic means a code is written with idiomatic style, you can’t understand what it does with one-to-one translation (you can’t use python basics to understand it), you have to understand it with some prior knowledge. This article aims to give you some of that knowledge.
1- Built-in Functions
Let’s start with an easy one.
To get a slice from a list, you will probably use this annotation:
array[:2]
This annotation actually calls a built-in function called slice. As it is obvious in this example, using for loops to get a slice of your data will result in a bad usage of resources.
So for any algorithm you developed, you should first check if you can use built-in functions [1] instead of trying to implement them by yourself.
2- Context Managers
There will always be some data that will be used in your code. This data can be coming from a file or database.
When you finished the job with your file or database, you may want to close the file or disconnect from the database. This is why people use with statement in python. But there is always a probability for an exception to happen. Are you going to handle it with lots of try and excepts?
A good way to handle these situations is to use a class with __enter__ and __exit__ magic functions. These are the functions that will be called when entered or exited the runtime context related to the object of that class with the with statement.
Here is an example code from the book Clean Code in Python[2]. This code is trying to disconnect from the database to take a backup. To handle any unexpected errors, it rewrites the __exit__ magic function to connect again with the database when the backup ended or when any exception is thrown.
This is definitely better than writing lots of code to handle all of the exceptions that may happen. The exception arguments in __exit__ function will be None if no exception happens.
Also, there is a better version of this that uses contextmanager.
This is what I call a Pythonic code. You first have to know how context managers work and second, you have to know that try represents __enter__, finally represents __exit__.
Contextlib is a python standard library having utilities for with-statement contexts. You can check all python standard libraries here: https://docs.python.org/3/library/
Also, these codes are from the book[2], and I highly recommend you to read the book. It has more examples on this topic which you may want to learn.
3 — Data Classes
Data classes are classes that are meant to hold data. The purpose of dataclass is to make classes easier to use as data containers. It makes your code more compact and understandable. Here is an example of dataclass from a great article[3].
Let’s look at it one by one.
- You don’t have to define an __init__ function, instead, you give the variable names and their types, it handles the rest for you.
- It forces you to use type annotations, which is good for many things.
- You can easily give default values (not mandatory), if you wanted to use this with default classes, you’d have to use lots of if else statements.
- You can easily compare two instances if they have same values for same variables. If you wanted to use this with default classes, you’d have to overwrite __eq__ magic function.
These are just the beginning, you can check more details on this topic at [3] and [4]. There are much more things that can be done with dataclass but this example is enough to start using it.
I hope you enjoyed and learned something. I highly recommend you implement these yourself and then read the references to get a deeper understanding.
If you have read this far, you may want to check other articles we have been publishing as Carbon Consulting.
References:
1 —Python Built-in Functions, https://docs.python.org/3/library/functions.html
2 — Clean Code in Python, Develop Maintainable and Efficient Code, 2nd Edition, Mariano Anaya https://www.amazon.com/Clean-Code-Python-maintainable-efficient/dp/1800560214
3— 9 Reasons Why You Should Start Using Python Dataclasses, https://towardsdatascience.com/9-reasons-why-you-should-start-using-python-dataclasses-98271adadc66
4— Data Classes in Python 3.7+ (Guide), https://realpython.com/python-data-classes/
5 — https://realpython.com/learning-paths/writing-pythonic-code/