How to fix Python indentation
python
Solution
Use the `reindent.py` script that you find in the `Tools/scripts/` directory of your Python installation:
Change Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files. Also ensure the last line ends with a newline.
Have a look at that script for detailed usage instructions.
NOTE: If your linux distro does not have reindent installed by default with Python:
Many linux distros do not have `reindent` installed by default with `python` --> one easy way to get `reindent` is to do `pip install reindent`.
p.s. An alternative to `pip` is to use your distros package manager (i.e. `apt-get`, `yum`, `dnf`) but then you need to figure out what package has the command line tool because each distro has the tool in a different package.
Problem
I have some Python code that have inconsistent indentation. There is a lot of mixture of tabs and spaces to make the matter even worse, and even space indentation is not preserved. The code works as expected, but it's difficult to maintain. How can I fix the indentation (like HTML Tidy, but for Python) without breaking the code? Some editor-specific advice: Vi/Vim: - Replace tabs with spaces in vim - Expand tabs to spaces in vim only in python files? - Use Vim Retab to solve TabError: inconsistent use of tabs and spaces in indentation? - How to maintain tabs when pasting in Vim Notepad++: - Convert tabs to spaces in Notepad++ - Auto-indent in Notepad++ - How do I configure Notepad++ to use spaces instead of tabs? Emacs: - Indentation not working properly in emacs for python - Emacs bulk indent for Python Eclipse: - indent python file (with pydev) in eclipse Visual Studio Code: - Visual Studio Code indentation for Python
Related problems
- Expand tabs to spaces in vim only in python files?
- Tool to convert Python code to be PEP8 compliant
- Emacs bulk indent for Python
- Replace tabs with spaces in vim
- Convert tabs to spaces in Notepad++
- Use Vim Retab to solve TabError: inconsistent use of tabs and spaces in indentation?
- How do I configure Notepad++ to use spaces instead of tabs?
- Visual Studio Code indentation for Python