[Python]: Auto-Format Code According to PEP 8

Level of Difficulty: Beginner to Senior.

So you’ve written a Python Script, Kevin has just told your team that all code needs to be reviewed and part of the team’s Key Performance Indicators (KPIs) will be PEP 8 compliance.

Now there’s a slight sense of chaos and stress because “What is PEP 8?! Can one eat it? Is it something that we take to retro?” Mark has a minor panic attack because, not only does he not know what PEP 8 is, but how on earth will he enforce it? Joan is passive but has reservations because the “rather complex” script has already been written, how will she refactor it all in time for her 3PM appointment with Call of Duty?

Don’t worry Joan (and team)… We’ve got you covered! It’s rather important to know what PEP 8 is but as for enforcing it, there are libraries that will assist in doing it for you.

But wait… There’s more, Kevin might even use one of these libraries to check if PEP 8 has been adhered to. Here’s how with the Black and\or autopep8 libraries.

What are the steps?

The steps that we will be following are:

  1. Find out what PEP 8 is
  2. Create the Python script
  3. Decide which library to use (black and\or autopep8) and install it
  4. Format your script

Deep Dive

Let’s dive deeper into the steps listed above.

What’s PEP 8?

PEP 8 is a set of standards and coding styling guides for Python code. Keeping code consistent and in accordance to a set of standards makes code easy to debug and maintain.

Let’s check it out in action.

Create The Python Script

Mark would like to experiment with this “Auto Black 8 and PEP” concept, so he creates a basic python script and saves it to C:\Python Scripts\PEPTest.py:

import sys, os
# try to print the current Python interpreter path and current working directory path
def print_paths():
	try:
		print(sys.executable)
		print(os.getcwd())
	except Exception as e:
		print(e)
print_paths()

Install Selected Library

Joan explains to Mark that he should definitely check this blog post out, then test the capability of black before testing autopep8 and deciding which one he would like to use. So off Mark goes to follow Joan’s advice.

Black

Mark installs the black library using the following command from command line:

py -m pip install black --user

Now that black has been installed, Mark runs the following command to see which commands he can use with black:

py -m black -h

The following catch Mark’s eye:

–check Don’t write the files back, just return the status.
–diff Don’t write the files back, just output a diff for each file on stdout.

Mark decides to check if there would be changes if he were to use black by using the –check argument:

py -m black PEPTest.py --check

Mark sees the following in the command line:

Now that he knows his code will be formatted, he wants to see how they would be formatted so he runs the following command:

py -m black PEPTest.py --diff

Mark sees the following in the command line:

Mark is experiencing excitement and tingles in places. Now he wants to see if this will actually change his code, so he runs the following code:

py -m black PEPTest.py

He opens up the file in Notepad and sees that his code has been formatted!

Now he wants to see if autopep8 does the same.

Autopep8

Mark replaces the formatted code with the following:

import sys,os
# try to print the current Python interpreter path and current working directory path
def print_paths():
    try:
        print(sys.executable)
        print(os.getcwd())
    except Exception as e:
        print(e)
print_paths()

Mark installs the autopep8 library using the following command from command line:

py -m pip install autopep8 --user

Now that black has been installed, Mark runs the following command to see which commands he can use with black:

py -m autopep8 -h

The following catch Mark’s eye:

–aggressive enable non-whitespace changes; multiple -a result in more aggressive changes
–in-place make changes to files in place
–diff print the diff for the fixed source

Mark decides to see if there would be changes if he were to use black by using the –diff argument:

py -m autopep8 PEPTest.py --diff

Mark sees the following in the command line:

Now he wants to see if this will actually change his and how “aggressive” it really is, so he runs the following code:

py -m autopep8 PEPTest.py --aggressive

For giggles, he adds –in-place to see what happens. He sees the following:

He opens up the file in Notepad and sees that his code has been formatted!

In the meantime, Joan had run through the same steps and after more confederating around the coffee machine, they came to a consensus that the “aggressive” use of autopep8 seems to be more beneficial to the team and as such, that’s what they would use to format their code before sending it for review.

Kevin decided he would stick to black for code review. Jokes on him right?

Wrong? Drop your comment below or reach out to jacqui.jm77@gmail.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: