python에서는 pep8 코드 컨벤션에 맞게 코드를 자동으로 서식을 맞춰주는 “autopep8″이라는 자동 formatter가 존재합니다.
이번 포스트에서는 autopep8 설치, 사용법, 또 필요에 따라 설정을 변경하는 법을 정리해보았습니다.
autopep8 설치

extension 아이콘 클릭 -> autopep8 검색 -> autopep8 확장팩 설치
autopep8 설정
vscode에서 formatter를 설정하기 위해, ctrl + ,
단축키를 눌러 vscode 설정으로 진입합니다.
이후 설정에서 python formatting을 검색하고, Python > Formatting: Provider 설정을 찾아 autopep8로 설정해줍니다.

저장 할 때 마다 자동으로 autopep8 실행시키기
이후 파일이 저장 될 때 자동으로 formatter를 실행시키기 위해, format on save를 검색 한 후 설정을 활성화 시켜줍니다. 해당 설정을 활성화 시키면 파일이 저장될 때 자동으로 formatter가 실행되며, 설정하지 않은 경우 수동으로 formatter를 실행시켜야 합니다.

설정 완료 후 vscode를 재시작하면 자동 formatter가 적용됨을 알 수 있습니다.
autopep8 실행 전
아래 예제 코드를 보면 공백 규칙과 주석 규칙을 지키지 않은 것을 확인 할 수 있습니다.
이제 여기서 Ctrl + S를 저장을 시킵니다.

atuopep8 실행 후
Ctrl + S 로 저장하면 자동으로 autopep8가 실행되며 formatting까지 맞춰지는 것을 확인 할 수 있습니다.

autopep8이 작동되지 않는 경우, 옵션에 없는 경우
autopep8이 python formatting 옵션에서 안 뜨는 경우는 설정을 바꿔줘야 합니다. 자세한 내용은 아래 포스트를 확인해주세요.

max line length 조절하기 (autopep8 config 조정하기)
autopep8을 써준다고 해서 모든 코딩 컨벤션을 따르게 하는 것은 아닙니다. 아래 예를 확인해보겠습니다.
PEP 규칙에 아래와 같은 규칙이 있습니다.
- PEP8은 79자로 끊기를 제안
하지만 이런 규칙은 autopep8로 지켜지지 않습니다. 아래 코드 한 줄이 굉장히 긴 코드를 확인해주세요.

autopep8이 적용되면 아래와 같이 됩니다. 띄어쓰기 및 주석은 PEP8에 맞게 변경되었지만 코드의 길이가 길다고 해서 줄 개행까지 진행해주지는 않습니다.

이런 줄 끊기 옵션은 대신에 autopep8의 세팅을 바꿈으로써 해결할 수 있습니다.
settings에 들어가 autopep8을 입력합니다.

Arg의 Add Item을 클릭합니다. Add를 누른 후 --max-line-length
를 입력합니다.

차례로 79, –experimental을 입력해줍니다.

입력을 완료하면 아래와 같습니다.

저장 후, VScode를 재시작 합니다.
max line length 변경 전
이제 다시 한번 autopep로 formatting해보겠습니다.

max line length 변경 후

autopep8 규칙 변경
autopep8에서 특정 규칙이 작동 안되도록 수정할 수 있습니다. 물론 남들과 다른 규칙을 적용하면 협업 때 코드가 쓸데없이 변경됨으로 혼란을 야기할 수 있기에 규칙은 건들지 않는 게 좋습니다. 그래도 사용자가 원하는 경우 특정 규칙을 통제할 수 있습니다.
아래 예제를 보면 autopep8을 작동시킴으로써 indent도 수정하고 메서드 사이에 blank line도 추가되는 것을 볼 수 있습니다.

여기서 사용자가 메서드 사이에 blank line 되는 기능을 제거하고 싶다면 옵션에 해당 사항을 추가할 수 있습니다.
settings 메뉴에서 autopep8을 입력 후 Args setting에 Add item 클릭 –ignore을 입력하고 반복해서 Add item 클릭 E301을 입력합니다.
(E301은 누락된 blank line을 추가해주는 규칙입니다)
settings 변경 후 VScode를 재시작 해줍니다.

이제 autopep8를 적용하면 인덴트를 이전과 동일하게 수정되지만 메소드 사이에 blank line이 추가하는 규칙은 제거 되었음을 확인 할 수 있습니다.

여러가지 규칙을 변경해줄 수 있습니다.
아래는 규칙 코드 입니다. ignore 인자에 추가함으로써 해당 규칙을 제거할 수 있습니다.
E101 - Reindent all lines.
E11 - Fix indentation.
E121 - Fix indentation to be a multiple of four.
E122 - Add absent indentation for hanging indentation.
E123 - Align closing bracket to match opening bracket.
E124 - Align closing bracket to match visual indentation.
E125 - Indent to distinguish line from next logical line.
E126 - Fix over-indented hanging indentation.
E127 - Fix visual indentation.
E128 - Fix visual indentation.
E129 - Fix visual indentation.
E131 - Fix hanging indent for unaligned continuation line.
E133 - Fix missing indentation for closing bracket.
E20 - Remove extraneous whitespace.
E211 - Remove extraneous whitespace.
E22 - Fix extraneous whitespace around keywords.
E224 - Remove extraneous whitespace around operator.
E225 - Fix missing whitespace around operator.
E226 - Fix missing whitespace around arithmetic operator.
E227 - Fix missing whitespace around bitwise/shift operator.
E228 - Fix missing whitespace around modulo operator.
E231 - Add missing whitespace.
E241 - Fix extraneous whitespace around keywords.
E242 - Remove extraneous whitespace around operator.
E251 - Remove whitespace around parameter '=' sign.
E252 - Missing whitespace around parameter equals.
E26 - Fix spacing after comment hash for inline comments.
E265 - Fix spacing after comment hash for block comments.
E266 - Fix too many leading '#' for block comments.
E27 - Fix extraneous whitespace around keywords.
E301 - Add missing blank line.
E302 - Add missing 2 blank lines.
E303 - Remove extra blank lines.
E304 - Remove blank line following function decorator.
E305 - Expected 2 blank lines after end of function or class.
E306 - Expected 1 blank line before a nested definition.
E401 - Put imports on separate lines.
E402 - Fix module level import not at top of file
E501 - Try to make lines fit within --max-line-length characters.
E502 - Remove extraneous escape of newline.
E701 - Put colon-separated compound statement on separate lines.
E70 - Put semicolon-separated compound statement on separate lines.
E711 - Fix comparison with None.
E712 - Fix comparison with boolean.
E713 - Use 'not in' for test for membership.
E714 - Use 'is not' test for object identity.
E721 - Use "isinstance()" instead of comparing types directly.
E722 - Fix bare except.
E731 - Use a def when use do not assign a lambda expression.
W291 - Remove trailing whitespace.
W292 - Add a single newline at the end of the file.
W293 - Remove trailing whitespace on blank line.
W391 - Remove trailing blank lines.
W503 - Fix line break before binary operator.
W504 - Fix line break after binary operator.
W605 - Fix invalid escape sequence 'x'.
W690 - Fix various deprecated code (via lib2to3).
참고할 만한 글


I appreciate you sharing this blog post. Thanks Again. Cool.
I’m glad you found it helpful!