PEP 8-Style Guide for Python Code

PEP8 - Style Guide for Python Code Python 코드의 스타일 가이드로, 가독성과 일관성을 높이기 위한 다양한 규칙과 권장사항을 제시한다. 중요한 점은 이 가이드라인들은 제안사항이며, 프로젝트의 일관성이 더 중요하다. 기존 코드의 스타일을 존중해야 한다. 일부 규칙은 특수한 상황에서 무시될 수 있다. 가독성이 최우선. 프로젝트별로 자체적인 스타일 가이드가 있을 경우 해당 가이드를 우선시 코드 레이아웃 (Code Layout) 들여쓰기 (Indentation) 4개의 스페이스를 사용. 연속된 줄은 괄호 안에서 수직으로 정렬하거나 hanging indent를 사용한다. 탭은 사용하지 않음. 탭과 공백은 혼용하지 않는다. 라인 길이 최대 79자 문서화 문자열(docstring)과 주석은 72자 긴 줄은 여러 줄로 나누어 작성. 줄 연결은 괄호나 백슬래시를 사용한다. 줄바꿈 연산자 앞에서 줄을 바꾸는 것이 더 가독성이 좋다. 올바른 예 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 # 괄호 안에서 수직 정렬 foo = long_function_name(var_one, var_two, var_three, var_four) # Hanging indent def long_function_name( var_one, var_two, var_three, var_four): # 함수 내용은 4칸 들여쓰기 print(parameter_1) # if문도 4칸 들여쓰기 if True: # if문 내부는 추가로 4칸 들여쓰기 print("Nested content") # 여러 줄의 리스트 my_list = [ 1, 2, 3, 4, 5, 6 ] 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()) # 1. 괄호를 사용한 줄 나누기 long_string = ( "이것은 매우 긴 문자열이라서 " "여러 줄로 나누어 작성했습니다." ) # 2. 연산자 앞에서 줄 바꾸기 total = ( first_variable + second_variable - third_variable ) income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) # 3. 함수 인자 나누기 def long_function_name( var_one, var_two, var_three, var_four): print(var_one) 잘못된 예 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 # 인자가 첫 줄에 있으면 안 됨 foo = long_function_name(var_one, var_two, var_three, var_four) def long_function_name( parameter_1, # 2칸만 들여씀 parameter_2, parameter_3 # 불필요하게 많이 들여씀 ): print(parameter_1) # 탭 사용 if True: print("Wrong indent") # 3칸만 들여씀 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()) # 1. 한 줄이 너무 김 long_string = "이것은 매우 긴 문자열이라서 한 줄에 전부 작성하면 79자를 훨씬 넘어가게 되어 가독성이 떨어지게 됩니다." # 2. 잘못된 줄 나누기 total = first_variable + \ second_variable + \ third_variable income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) # 3. 잘못된 함수 인자 나누기 def long_function_name(var_one, var_two , var_three, var_four): # 쉼표가 잘못된 위치에 있음 print(var_one) 임포트 (Import) 임포트는 항상 파일의 맨 위에 작성한다. 각 임포트는 별도의 줄에 작성한다. 임포트는 다음 순서로 그룹화한다. 표준 라이브러리 관련된 서드파티 라이브러리 로컬 애플리케이션 / 라이브러리 올바른 예 1 2 3 4 5 6 7 8 9 10 11 12 13 # 1. 표준 라이브러리 import os import sys from datetime import datetime, timedelta # 2. 서드파티 라이브러리 import numpy as np import pandas as pd # 3. 로컬 애플리케이션 from myproject.models import User from myproject.utils import helper from . import localmodule 잘못된 예 1 2 3 4 5 6 7 8 9 10 11 12 13 # 1. 한 줄에 여러 임포트 import sys, os, datetime # 2. 잘못된 순서 from myproject.models import User import os import pandas as pd # 3. 와일드카드 임포트 from mymodule import * # 이것은 피해야 함 # 4. 불필요한 임포트 from mymodule import MyClass, MyClass # 중복 표현식과 문장의 공백 적절한 공백 사용은 코드의 가독성을 크게 향상시킨다. 일관된 공백 사용이 중요하다. 괄호, 대괄호, 중괄호 안쪽에 불필요한 공백을 넣지 않는다. 쉼표, 세미콜론, 콜론 앞에는 공백을 넣지 않는다. 올바른 예 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 # 1. 할당 연산자 x = 1 y = 2 # 2. 연산자 result = x + y * (z - 1) # 3. 쉼표 후 공백 items = [1, 2, 3, 4, 5] def func(x, y, z): pass if x == 4: print(x, y); x, y = y, x # 1. 괄호 spam(ham[1], {eggs: 2}) # 2. 딕셔너리 dict = {'key': 'value'} # 3. 리스트/튜플 list = [1, 2, 3] tuple = (1, 2, 3) 잘못된 예 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 # 1. 불일치하는 공백 x=1 y= 2 z =3 # 2. 연산자 주변 공백 누락 result=x+y*(z-1) # 3. 쉼표 후 공백 누락 items = [1,2,3,4,5] def func(x,y,z): pass if x == 4 : print(x , y) ; x , y = y , x # 1. 불필요한 공백 spam( ham[ 1 ], { eggs: 2 } ) # 2. 불일치하는 공백 dict = { 'key':'value' } dict = {'key' :'value'} # 3. 리스트/튜플의 불필요한 공백 list = [ 1,2,3 ] tuple = ( 1,2,3 ) 명명 규칙(Naming Conventions) 일관된 이름 규칙은 코드의 가독성을 높인다. 의미 있고 설명적인 이름을 사용해야 한다. 타입 규칙 예시 설명 패키지/모듈 짧은 소문자 필요시 언더스코어 utils email_validator data_parser 모듈은 import 시 파일명이 되므로 짧고 간단하게 작성 클래스 CapWords(Pascal Case) UserProfile EmailValidator DatabaseConnection 각 단어의 첫 글자를 대문자로 작성 함수/메서드 소문자 + 언더스코어 (snake_case) calculate_total() get_user_info() validate_email() 기능을 명확히 설명하는 동사로 시작 변수 소문자 + 언더스코어 (snake_case) user_name total_count items_list 데이터의 내용을 명확히 설명 상수 대문자 + 언더스코어 MAX_VALUE DEFAULT_TIMEOUT PI 변경되지 않는 값임을 명확히 표시 보호 속성 앞에 언더스코어 1개 _internal_name _protected_method() 직접 접근을 권장하지 않는 내부 사용 속성 비공개 속성 앞에 언더스코어 2개 __private_name __private_method() 클래스 외부에서 접근을 제한하는 속성 특별 메서드 앞뒤 더블 언더스코어 __init__ __str__ __len__ Python에서 특별한 의미를 가진 메서드 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 # 1. 패키지/모듈 예시 import email_validator from data_processing import utils # 2. 클래스 예시 class UserProfile: def __init__(self, name): self.name = name class EmailValidator: def validate(self, email): pass # 3. 함수/메서드 예시 def calculate_total(items): return sum(items) def get_user_info(user_id): pass # 4. 변수 예시 first_name = "John" total_count = 0 items_list = [] # 5. 상수 예시 MAX_CONNECTIONS = 100 DEFAULT_TIMEOUT = 30 PI = 3.14159 # 6. 클래스에서의 보호/비공개 속성 예시 class Customer: def __init__(self): self._internal_id = 123 # 보호 속성 self.__private_data = "secret" # 비공개 속성 def _protected_method(self): # 보호 메서드 pass def __private_method(self): # 비공개 메서드 pass def __str__(self): # 특별 메서드 return f"Customer {self._internal_id}" 추가적인 명명 규칙 지침: ...

November 26, 2024 · 22 min · Me