The popularity of Python has attracted many developers from other languages, that sometimes incorporate their original code style into Python development. It is common to see Python code that looks like Java or C++.
For this reason, the concept of pythonic was coined. A pythonic code is a code that follows a set of principles and conventions for using Python in the way it is intended to be used. These conventions are defined by Guido Van Rossum, benevolent dictator for life (until he resigned in July 2018), and by the community.
In an effort to provide some guiding principles on how to write better Python code, Tim Petters wrote the Zen of Python. The second aphorism reads:
Explicit is better than implicit
Being explicit means being concrete and specific instead of abstract and general. It also means not to hide the behavior of a function.
In the next example, we use the library requests to do a GET request to a URL. In the explicit behavior, it is clear that the function is from the library requests, whereas in the implicit behavior, there could be a conflict if another function in the code is called get.
# Explicit
import requests
r = requests.get("https://miguelgfierro.com")
# Implicit
from requests import *
r = get("https://miguelgfierro.com")
Another good example of explicit behavior can be seen in the Pandas IO functions. The IO functions for reading CSV or JSON format are explicitly defined as pd.read_csv and pd.read_json. An implicit behavior would have been to have a common interface, maybe called read, and manage internally the different inputs.
#Explicit
def read_csv(filename):
# code for reading a csv
def read_json(filename):
# code for reading a json
#Implicit
def read(filename):
# code for reading a csv or json
# depending on the file extension
Be explicit my friend!