본문 바로가기
프로그래밍/독학(어려워요 같이해요)

파이썬 코딩할 때 전문가처럼 코딩해보기. Style Guide for Python Code 따르기.

by 노마드데이터랩 2021. 5. 15.
728x90
반응형

PEP 8-Python 코드 용 스타일 가이드에서 가장 티가 많이나는 코드 정렬 몇개를 추려보았습니다.

코드 스타일 가이드가 중요한 이유는 다른 분들과 협업을 하거나, 다른 사람의 코드를 볼 때 가독성이 좋습니다. 코드의 가독성이 올라가면 협업하는 시간도 줄일 수 있고 생산성도 올라갈 수 있겠죠??

가볍게 읽고 아, 이런게 있구나 정도만 아시면 될 것 같습니다.

그럼 시작해보겠습니다.

 

함수안에 들어가는 인자는 줄을 맞춰서, 정렬을 해줍니다.

# Correct:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# Wrong:

# Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
    var_three, var_four)

 

함수 안의 인자를 줄을 바꿔서 넣을 때는, 스페이스 4번을 눌러서 정렬을 해주세요.

#Correct 

# Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest.
def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)
    
    
# Wrong:

# Further indentation required as indentation is not distinguishable.
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

 

들여쓰기에서 연산자는 변수 다음 줄에 와야한다.

# Correct:
# easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)
          
# Wrong:
# operators sit far away from their operands
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)

 

임포트를 선언할 때는, 별도의 줄로 선언을 해야한다.

# Correct:
import os
import sys

# Wrong:
import sys, os

대신, from이 포함되는 경우 import 내에 여러 라이브러리를 같이 쓸 수 있다.

# Correct:
from subprocess import Popen, PIPE

 

대괄호, 중괄호의 안의 변수는 괄호와 붙여써야 합니다.

# Correct:
spam(ham[1], {eggs: 2})
# Wrong:
spam( ham[ 1 ], { eggs: 2 } )

 

괄호 안에서 쉼표로 끝나는 경우에, 쉼표와 괄호는 붙여야 한다.

# Correct:
foo = (0,)
# Wrong:
bar = (0, )

 

함수와 세미콜론, 콜론은 붙여 써줘야 합니다.

# Correct:
if x == 4: print x, y; x, y = y, x
# Wrong:
if x == 4 : print x , y ; x , y = y , x

 

함수를 불러올 때, 함수와 인자는 붙여줘야 합니다.

# Correct:
spam(1)
# Wrong:
spam (1)

 

변수를 정의할 때, 연산자의 위치는 변수를 기준으로 정렬합니다.

# Correct:
x = 1
y = 2
long_variable = 3

# Wrong:
x             = 1
y             = 2
long_variable = 3

 

변수 내 연산을 할 경우에 변수끼리 그룹을 묶어줍니다.

# Correct:
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

# Wrong:
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)

 

함수에 화살표를 적용하는 경우에 괄호에서 한칸 띄워줍니다.

# Correct:
def munge(input: AnyStr): ...
def munge() -> PosInt: ...

# Wrong:
def munge(input:AnyStr): ...
def munge()->PosInt: ...

 

인수 리스트가 사용될 때, 다음 줄에 각각 정의해줍니다.

# Correct:
FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initialize(FILES,
           error=True,
           )
           
# Wrong:
FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)

 

함수에는 예외성이 없어야 합니다.

# Correct:

def foo(x):
    if x >= 0:
        return math.sqrt(x)
    else:
        return None

def bar(x):
    if x < 0:
        return None
    return math.sqrt(x)
    
# Wrong:

def foo(x):
    if x >= 0:
        return math.sqrt(x)

def bar(x):
    if x < 0:
        return
    return math.sqrt(x)

https://www.python.org/dev/peps/pep-0008/

 

PEP 8 -- Style Guide for Python Code

The official home of the Python Programming Language

www.python.org

 

 

728x90
반응형

댓글