PEP-8

Daki·2023년 1월 24일
0

기본기

목록 보기
1/1
post-thumbnail

python을 주력으로 쓰는데, PEP 8은 읽어봐야지!

1. Indentation


  • 인자를 여러 줄에 걸쳐서 작성할 때는, 열-정렬을 해서 작성할 것.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)
  • 열-정렬을 하지 않고 여러 줄에 걸쳐서 쓸 때는, 첫 번째 줄에는 인자를 쓰지 말고, indent로 구분할 것.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)
  • indent가 연속 될 경우에는, 구분할 수 있게 indent를 추가로 줄 것.
def long_function_name(
        var_one, var_two, var_three,
        var_fout):
    print(var_one)
  • if문 조건이 복잡할 때, (추가 indent or 주석)으로 시각적 구분을 줄 것.
# 시각적 구분이 힘든 상태
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# 주석 & 하이라이터로 시각적 구분
if (this_isone_thing and
    that_is_another_thing):
    # Since both conditions are true, we can forbnicate.
    do_something()

# 추가 indent로 시각적 구분 
if (this_is_one_thing
        and that_is_another_thing):
    do_something()
  • 멀티라인 작성시에는, (첫 번째 인자 | 라인 처음)에 괄호를 닫을 것.
# 첫번 쨰 인자 위치에 닫기
my_list = [
    1, 2, 3,
    4, 5, 6,
    ]
# 라인이 시작된 위치에 닫기
result = some_function_thar_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)

멀티라인 작성을 할 때, 가능하다면 열-정렬을 할 것.
indent가 한 눈에 구분이 안될 때는, (주석 | 추가 indent)를 사용할 것.

2. 이항 연산자의 개행


  • 개행을 하고 이항 연산자를 기입할 것.
# 기존 방식
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)
 
 # 개행 후, 이항 연산자
 income = (gross_wages
           + taxable_interest
           + (dividends - qualidied_dividens)
           - ira_deduction
           - student_loan_interest)

3. import


  • 한 줄에 하나만 할 것, from ~ 은 여러개 허용.
import os
import sys

from subprocess import Popen, PIPE
  • import 순서
  1. Standard library
  2. Reladted third party
  3. Local app/library specific

1, 2, 3번의 사이에는 빈 줄을 넣어 시각적 구분을 줘야 한다.

  • 절대 경로로 import를 할 것이며, 구조가 너무 복잡할 경우에는 명시적 상대 경로 import를 한다.
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example
from . import sibling
from .sibling import example
  • Wildcard import는 namespace를 복잡하게 하므로 기피할 것. 쓸 경우에는 republish를 해야한다.

  • docstring 다음에, future_import를 적고,
    dunder로 정보를 기입한 후에, import를 해야한다.

"""This is the example module.
This module does stuff.
"""

from __future__ import barry_as_FLUFL

__all__ = ['a', 'b', 'c']
__version__ = '0.1'
__author__ = 'Cardinal Biggles'

import os
import sys

4. String Quotes


'과 "를 뭘 사용할지는 자유이다. 일관성만 지키면 된다.
단, triple-quoted는 "로 해야한다.

5. Expressions과 Statements에서의 공백


쓸모 없는 공백, 가독성을 흐리는 공백을 피해야 한다.

  • 괄호 바로 안에 공백을 붙이지 말 것.
# 좋은 예
spam(ham[1], {eggs: 2})

# 나쁜 예
span( ham[ 1 ], { eggs: 2 })
  • ,와 괄호가 이어질 때, 공백을 주지 말 것.
# 좋은 예
foo = (0,)

# 나쁜 예
bar = (0, )
  • comma, semicolon, colon 직전에 공백을 주지 말 것.
# 좋은 예
if x == 4: print(x, y); x, y = y, x

# 나쁜 예
if x == 4 : print(x , y) ; x , y = y , x
  • slicing은 이항 연산자 처럼 처리한다. 양쪽에 균일한 공백을 준다, 파라미터 생략시에는 주지 않는다.
# 좋은 예
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]

# 나쁜 예
ham[lower + offset:upper + offest]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]
  • indexing, slicing, function call 괄호에 공백을 주지 말것.
# 좋은 예
spam(1)
dct['key'] = lst[index]

# 나쁜 예
spam (1)
dct['key'] = lst [index]
  • 다른 연산자와 정렬하기 위해 두 개 이상의 공백을 주지 말 것.
# 좋은 예
x = 1
y = 1
long_variable = 3

# 나쁜 예
x             = 1
y             = 1
long_variable = 3
  • 할당 연산자, 비교 연산자, Boolean 양 옆에는 공백을 하나 씩 줄것.
  • 우선순위가 섞여있을 경우 구분을 위해서, 우선순위가 낮은 것에만 공백을 줄 것.
# 좋은 예
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

# 나쁜 예
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
  • function-annotation에서, colon은 평소 규약을 따르고 ->는 양 옆에 한칸 씩 공백을 줄 것.
# 좋은 예
def munge(input: AnyStr): ...
def munge() -> PosInt: ...

# 나쁜 예
def munge(input:anyStr): ...
def munge()->PosInt: ...
  • keyword-argument나 default-value의 =에는 공백을 주지 말것.
# 좋은 예
def complex(real, imag=0.0):
    return magic(r=real, i=imag)

# 나쁜 예
def complex(real, imag = 0.0):
    return magic(r = real, i = imag)
  • function-annotation과 default-vaule를 같이 쓸 때는 공백을 줄 것.
# 좋은 예
def munge(sep: AnyStr = None): ...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ... 

# 나쁜 예
def munge(input: AnyStr=None): ...
def munge(input: AnyStr, limit = 1000): ...
  • 한 줄에 여러줄을 이어서 적는 것은 지양할 것.
# 좋은 예
if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

# 나쁜 예
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

6. Trailing Commas


  • tuple 등을 사용할 경우에, 명시적으로 괄호를 사용할 것.
# 좋은 예
FILES = ('setup.cfg',)

# 나쁜 예
FILES = 'setup.cfg',
  • Trailing Commas가 연속적이고, version control system을 사용할 때, line_by_line으로 줄 것.
# 좋은 예
FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initalize(FILES,
          error=True,
          )
# 나쁜 예
FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)

7. Comments


  • 주석이 없는것 보다 잘못 된 주석이 더 나쁘다! 주석은 언제나 최신화 할 것!
  • 완전한 문장으로 구성하고, 마침표로 끝낼 것.
  • multi_line 주석에서는 문장 끝에 공백 2칸 후 기술할 것.
  • 영어로 작성할 것.
  • block_comment를 지향하고, inline_comment을 지양할 것.

8. DocString


  • 한 줄 DocString은 자명한 경우에 사용한다.
def kos_root():
    """Return the pathname of the KOS root directory."""
    global _kos_root
    if _kos_root: return _kos_root
    ...
  • multi-line DocString은 상세히 기술하고, 개행 후 """을 닫을 것.
def complex(real=0.0, imag=0.0):
    """Form a complex number.
    
    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero
    ...

9. Naming Conventions


  • l, O, I는 단독으로 변수명에 사용하지 말 것. 1, 0과 헷갈린다.
  • 모듈명은 짧게, 소문자로 짓는다.
  • 패키지명 규칙도 같지만 _를 지양한다.
  • 클래스명은 CamelCase를 따를 것.
profile
하기 싫어도 하자, 감정은 사라지고 결과는 남는다.

0개의 댓글