자동 포맷팅을 위해 autopep8 사용하기
Manually formatting code can be tedious. Fortunately, tools exist to automate this process. In this step, you will install and use autopep8, a popular tool that automatically reformats Python code to conform to the PEP 8 style guide.
First, you need to install the autopep8 package. Open the terminal and run the following command. sudo is used to install it system-wide.
sudo pip3 install autopep8
The installation process will begin, and you should see output confirming its successful installation:
Collecting autopep8
...
Successfully installed autopep8-X.Y.Z
Next, let's work with a Python file that has deliberately poor formatting. In the file explorer, open unformatted_code.py and examine its content:
a=1
b=2;
def my_function ( arg1 , arg2 = 0 ):
result = arg1+arg2
print( result)
This code has several style issues: inconsistent spacing, a redundant semicolon, and extra spaces in the function definition.
Now, let's use autopep8 to fix it. The --in-place flag tells the tool to modify the file directly. Run this command in your terminal:
autopep8 --in-place ~/project/unformatted_code.py
After the command finishes, open unformatted_code.py again in the editor. You will see that the code has been automatically cleaned up:
a = 1
b = 2
def my_function(arg1, arg2=0):
result = arg1 + arg2
print(result)
Notice how autopep8 corrected the spacing, removed the semicolon, and added two blank lines before the function definition, as recommended by PEP 8. Using an auto-formatter like autopep8 is a highly efficient way to maintain a consistent code style across your projects.