본문 바로가기

코딩/파이썬 기초

[Python] 파이썬 코딩 스타일 가이드, PEP 8

PEP 8 : Style Guide for Python Code

Author : Guido van Rossum, Barry Warsaw, Nick Coghlan

 

1) 들여쓰기 (Identation)

 

  • 4개의 빈칸 사용 (use 4 spaces per identation level)
# PEP 8에 기술되어 있는 들여쓰기 가이드 (일부)

foo = long_function_name(var_one, var_two,
                         var_three, var_four)

def long_function_name(
        var_one, var_two, var_three,
        var_four):
    print(var_one)

foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

if (this_is_one_thing and
    that_is_another_thing):
    # Since both conditions are true, we can frobnicate.
    do_something()

if (this_is_one_thing
        and that_is_another_thing):
    do_something()

my_list = [
    1, 2, 3,
    4, 5, 6,
    ]

result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )

 

2) 라인 별 최대 글자 수 (Maximum Line Lenght)

 

  • 라인 별 79자가 기준이나 좀 더 긴 글자 수를 선호한다면 99자까지 사용
with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

 

3) 연산자 위치 (Line break before/after a binary operator? -> before)

 

income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

 

4) 빈 라인 (Blank Lines)

 

  • 클래스 및 함수 앞엔 2칸
  • 클래스 내 메서드 앞엔 1칸
print('hello world')


# class -> 2 blank lines
class NewClass:
	
    # method -> 1 blank line
    def new_method(self):
    	pass


# funciton -> 2 blank lines
def new_function():
	pass

 

5) import

명시적인 import (from module import *와 같이 와일드카드 * 사용 지양)

 

1) Standard library imports

2) Releated third party imports

3) Local application/library specific imports

 

import sys
import os
from subprocess import Popen, PIPE

 

6) 문자열을 위한 따옴표

 

문자열 표현 시 작은 따옴표와 큰 따옴표에 대한 가이드는 두지 않으나, docstring은 큰 따옴표 사용

 

"""PEP 8 : Style Guide for Python Code"""

"""Welcome to my blog!
python
tkinter
kivy
"""

 

7) 공백 (whitespace)

 

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

# Trailing Commas
foo = (0,)
FILES = [
    'setup.cfg',
    'tox.ini',
    ]

if x == 4:
	print x, y
    x, y = y, x

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]

# function call
spam(1)

dct['key'] = lst[index]

x = 1
y = 2
long_variable = 3

# operators with different priorities
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

# Function annotation (space around ':' and '->')
def munge(input: AnyStr): ...
def munge() -> PosInt: ...

# Don't use spaces around '='
def complex(real, imag=0.0):
    return magic(r=real, i=imag)

# Argument annotation with a default value
def munge(sep: AnyStr = None): ...
def munge(input: AnyStr, sep: AnyStr = None, limit=1000): ...

 

8) 이름 짓기 (Naming Conventions)

 

'_'로 시작 --> 내부 사용을 표시 (single leading underscore)

(참고 : from M import * does not import objects whose names start with an underscore)

 

'_'로 끝남 -->  파이썬 키워드와의 충돌 회피 (single training underscore)

(예. class_ = 'ClassName')

 

'__'로 시작 --> 클래스 내에서 만 사용되는 속성임을 표시 (double leading underscore)

 

'__'로 시작하고 끝남 --> magic object or attribute. (double deading/tarining underscore)

 

파이썬 모듈 이름은 모두 소문자로 정의

 

클래스 이름은 CapWord(=Camel Case = 문자의 첫글자만 대문자)로 정의 (예. MyFirstClass)

 

함수 및 변수 이름은 모두 소문자에 의미 명확화를 위해 단어 사이 '_' 사용

 

상수(constant)는 모두 대문자로 정의 (예. PI = 원주율)

 

PI = 3.14159

class MyClass:

    _var_internal = int()
    class_ = 'My Class'
    __var_only_here = int()
    
    def method_name_one(self):
        pass
    
    def _method_name_two(self):
    	pass