Table of contents
For the past few days, I have made 2 pull requests to an open-source project. This was a great experience considering these are my baby steps in contributing to open-source projects. One of the new things I learned from the experience was using black to format the code before I could make a pull request. In this article, I would like to show how you can easily set up black and use it to format your Python code.
Black
Black is a popular code formatting tool for Python. It can automatically format Python code to conform to the PEP 8 style guide. It is especially useful for developers who need to adhere to a specific style guide or who are working on legacy code. Black can also help reduce merge conflicts, as developers using it will be using the same style across their codebase
Python Code
Let's write python code that has a dictionary and a function. The dictionary has an emoji as the key and the meaning of the emoji as the value.
The function will receive the emoji as the parameter and it will check the emoji in the dictionary. If the emoji exists, the function will return the meaning, or else it will return the string, not supported
.
d = {
"๐":"Grinning Face",
"๐":"Grinning Face with Big Eyes",
"๐":"Grinning Face with Smiling Eyes",
"๐":"Beaming Face with Smiling Eyes",
"๐":"Grinning Face with Sweat",
}
def meaning(emoji):
if emoji in d.keys():
return(d[emoji])
else:
return("not supported")
print(meaning("๐"))
Format code
We need to install black before we can use it, we can install it using pip install black
.
Now that black is installed, we can use it to format our code by running black main.py
. main.py
is the name of the file that contains our python code.
The command produces the following output:
reformatted main.py
All done! โจ ๐ฐ โจ
1 file reformatted.
Let's open the main.py
file and we should see it formatted:
d = {
"๐": "Grinning Face",
"๐": "Grinning Face with Big Eyes",
"๐": "Grinning Face with Smiling Eyes",
"๐": "Beaming Face with Smiling Eyes",
"๐": "Grinning Face with Sweat",
}
def meaning(emoji):
if emoji in d.keys():
return d[emoji]
else:
return "not supported"
print(meaning("๐"))
Black Flags
black also has an option that checks if the file should be formatted without modifying it. We can do this by adding the --check
flag.
If you would like to see what modifications black would make to the file without actually modifying it, we use the --diff
flag.
You can see more flags of the black command with black -h
Conclusion
In this article, we looked at using black to format our Python code to conform to the PEP 8 style guide.