Formatting python code

While reading open-source projects, have you ever wondered why some statements are written over multiple lines? For example,

def calculate_the_final_answer():
    pass

calculate_the_final_answer("This is a very long string", "This is another long string", "I don't know the length of this string")

becomes,

def calculate_the_final_answer():
    pass

calculate_the_final_answer(
    "This is a very long string",
    "This is another long string",
    "I don't know the length of this string",
)

This is to follow the standard style guide for python called PEP 8. PEP 8 states that character count in any line should not exceed 79(this scenario). But this is a difficult task for developers, to learn all the rules in order to follow the best styling.

PEP stands for Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python or its processes or environment. The PEP should provide a concise technical specification of the feature and a rationale for the feature. - PEP 1

This is where a formatter comes in. A formatter is any tool that converts our code according to a specific style guide. And the most famous formatter for Python is black. Black is so popular that it has amassed over 17k stars on GitHub till date. Black formatting stays as close to PEP8.

Install black

python3 -m pip install black
# or pip install black

Format .py files

python3 -m black -t py38 test.py
# or black -t py38 test.py

-t is the target for styling. In the above case, it's python 3.8.

Demo

black.gif

This is amazing. What's more amazing is that you can add this to your favorite IDEs, VSCode and Pycharm

Visual Studio Code

File > Preferences > Settings
or
`ctrl+,`

Now search format and python format

format on save.PNG

python formatter.PNG

PyCharm

File > Settings > plugins

Now search and install a new plugin named File Watchers

file watchers.PNG

After installing search for File watchers in settings. On the top-right corner, select + to add a new custom file watcher.

pycharm-sett.PNG

Make sure the scope is set to Project Files and the program path should be <path to black>. This can be done by using where

# windows
C:\Users\amals\Downloads>where black
C:\Users\amals\AppData\Roaming\Python\Python38\Scripts\black.exe
# linuxwhere black
/home/amalshaji/.local/bin/black

And finally set Black level to global so that you don't have to set for every project.

global.PNG

References

No Comments Yet