Tuesday, September 9, 2025

Python: fixing indentation in python

In python, indentation must consistent, runtime will report error if indentation inconsistent. 

It is hard if we use some editor to write the code. We can use black to fix it automatically base on pep 8 (Python Enhancement Proposal  8).

Installing black

# apt-get install black
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  python3-click python3-mypy-extensions python3-pathspec python3-platformdirs
Suggested packages:
  python-black-doc
The following NEW packages will be installed:
  black python3-click python3-mypy-extensions python3-pathspec
  python3-platformdirs
0 upgraded, 5 newly installed, 0 to remove and 1 not upgraded.
Need to get 1,502 kB of archives.
After this operation, 6,442 kB of additional disk space will be used.

Using black

$ black ./[your_python_file_to_fix].py
reformatted [your_python_file_to_fix].py

All done! ✨ 🍰 ✨
1 file reformatted.