Black Code Formatter
Disclaimer: This post has been translated to English using a machine translation model. Please, let me know if you find any mistakes.
If you have been programming in Python for a while, I suppose you know the PEP8, which is a style guide for writing code in Python, Black
Well, today I bring a Python code formatter that follows PEP8
so that your codes are more readable and maintainable both by others and by your future self.
Installation
To install it, we can install it with conda
conda install conda-forge::black
or with pip
pip install black
Example Code
I am going to create a file called sample_code.py
with the following code
class myClass:
def display_info(self, name, subname, age, description, address, city, zip_code, country, phone, email, license, departament):
return f"Name : {name}, Subname : {subname}, Age : {age}, Description : {description}, Address : {address}, City : {city}, Zip Code : {zip_code}, Country : {country}, Phone : {phone}, Email : {email}, License : {license}, Departament : {departament}"
def add_numbers(num1,
num2):
return num1 + num2
text = "This is some text"
letters = (
"alpha",
"beta",
"gamma",
"delta",
"epsilon",
"zeta",
"eta",
"theta",
"iota",
"kappa",
)
As we can see, it has the first two lines very long, the declaration of the second method in several lines, etc.
Formatting the Code
To format the code we have two options, do
black {source_file_or_directory}
or do
python -m black {source_file_or_directory}
So let's format it
!black sample_code.py
reformatted sample_code.pyAll done! ✨ 🍰 ✨1 file reformatted.
After formatting it, the code looks like this
class myClass:
def display_info(
self,
name,
subname,
age,
description,
address,
city,
zip_code,
country,
phone,
email,
license,
departament,
):
return f"Name : {name}, Subname : {subname}, Age : {age}, Description : {description}, Address : {address}, City : {city}, Zip Code : {zip_code}, Country : {country}, Phone : {phone}, Email : {email}, License : {license}, Departament : {departament}"
def add_numbers(num1, num2):
return num1 + num2
text = "This is some text"
letters = (
"alpha",
"beta",
"gamma",
"delta",
epsilon
"zeta",
"eta",
"theta",
"iota",
"kappa",
)
Much better, right?