Skip to content

Python PEP8 formatter

  • by

Python provides a command-line tool called autopep8 that can automatically format your code according to the PEP 8 style guide. To use autopep8, you need to have it installed on your system. You can install it using pip:

pip install autopep8

Once installed, you can format your Python code by running the autopep8 command followed by the name of the Python file you want to format.

autopep8 your_file.py

By default, autopep8 will modify the file in place, so make sure to create a backup of your code before running the command if you want to preserve the original version. If you want to preview the changes without modifying the file, you can use the --diff option:

autopep8 --diff your_file.py

This will display the differences between the original and formatted code without modifying the file. If you’re satisfied with the changes, you can run the command without the --diff option to apply the formatting.

autopep8 also provides various options to control the formatting process. For example, you can use the --aggressive option to apply more aggressive formatting:

autopep8 --aggressive your_file.py

You can find more information about autopep8 and its available options by running autopep8 --help in your terminal.

Python PEP8 formatter example

Let’s say you have the following Python code that doesn’t conform to PEP 8 style guidelines:

def    greet(   name )    :
    print   (   "Hello, "  +   name+"!"  )
  1. Install autopep8 if you haven’t already by running pip install autopep8 in your terminal.
  2. Create a backup of your code or make sure you have a copy in case you want to preserve the original version.
  3. Run the autopep8 command followed by the name of the Python file you want to format:

After running the command, the code will be formatted according to PEP 8. In this case, the output would be:

Python PEP8 formatter

Overwriting files with formatted code:

autopep8 --in-place your_file.py

As you can see, autopep8 applied several changes to adhere to PEP 8 guidelines. It removed unnecessary whitespace, added spaces around operators, and adjusted the indentation.

Do comment if you have any doubts or suggestions on this Python basic topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading