kongsberg
콩스버그
kongsberg
전체 방문자
오늘
어제
  • 분류 전체보기 (42)
    • DL&ML (29)
    • 웹프로그래밍 (2)
    • 상식 (3)
    • 재테크 (7)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 글자크기 조절
  • TMUX
  • llama2
  • pylint
  • instruction-pt
  • CMA
  • GPT
  • Llama
  • pytorch
  • llm pre-training
  • further pre-training
  • 토스뱅크
  • 거대언어모델
  • 재테크
  • 네이버통장
  • html 글자크기
  • 네이버CMA
  • llm code
  • LLM
  • CSS 글자크기

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
kongsberg

콩스버그

DL&ML

PEP 8 - Python 코드 스타일 가이드

2022. 10. 31. 19:29
728x90

참고한 링크 : https://peps.python.org/pep-0008/

Indentation (띄어쓰기)

# Correct:

# 괄호 정렬을 해야함
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# indentation은 다음 단계로 넘어갈 때마다 4칸씩 space 해줘야 함
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)

# Wrong:

# 괄호 정렬 안됨
foo = long_function_name(var_one, var_two,
    var_three, var_four)

# print문에서 indentation 한 번 더 해야함
def long_function_name(
    var_one, var_two, var_three,
    var_four):
    print(var_one)

list나 함수 arguments 올바른 indentation 방법

# Correct

my_list = [
    1, 2, 3,
    4, 5, 6,
    ]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )

# Correct

my_list = [
    1, 2, 3,
    4, 5, 6,
]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)

Taps or Spaces?

Spaces 가 선호된다. tabs을 쓰더라도 spaces와 혼용하지 말자. python은 spaces와 tab을 동시에 사용하는 것을 불허하기 때문이다.

Maximum Line length

79 글자가 limit이다.

Comment나 text 위주의 코드는 72 글자가 limit이다.

ex)

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())

사칙 연산과 줄 바꿈

# Wrong:

# 연산자 후에 줄바꿈 x
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)

#Correct

# 연산자 전에 줄바꿈
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

Source File Encoding

test 코드를 제외하곤, 오로지 UTF-8만 사용해야 함

Imports

# Correct:

import os
import sys

# Wrong:

import sys, os

# Correct:

from subprocess import Popen, PIPE

Imports의 grouping 순서

  1. 표준 라이브러리 imports
  1. Related third party imports
  1. Local application/library specific imports

ex)

# Correct:

import os
import sys

from sklearn import metrics
import numpy as np
import torch

from .Detectron2.utils import MaskRCNN
from .Detectron2.dataset import DetectionDataset

Module level “dunders” (Double underscore Methods)의 경우에는 맨 앞으로 배치해야함

ex)

# Correct:

"""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

따옴표 ‘ or “

둘 중 하나로 통일하면 됨. 혼용하지 않기

띄어쓰기

괄호 안쪽은 붙여쓰기

# 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

slice시에는 동일 간격 유지

# Correct:
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]

# Wrong:
ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]

변수 선언시 띄어쓰기는 한 번만

# 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)

Keyword argument를 할 때에는 띄어쓰지 말기

# Correct:
def complex(real, imag=0.0):
    return magic(r=real, i=imag)

# Wrong:
def complex(real, imag = 0.0):
    return magic(r = real, i = imag)

같은 줄에 multiple statemetns는 권장되지 않음


# Correct:
if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

# Wrong:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

Trailing Commas

괄호가 있을때만 마지막에 comma를 붙임

# Correct:
FILES = ('setup.cfg',)

# Wrong:
FILES = 'setup.cfg',

여러 변수끝에 trailing Commas를 사용할 때는 줄바꿈을 사용

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

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

Documentsation Strings (Docstrings)

마지막줄은 “””만 단독으로 사용하라.

한 줄일 때만 같은 줄에 사용.

ex)

"""Return a foobang

Optional plotz says to frobnicate the bizbaz first.
"""

"""Return an ex-parrot."""

Naming

Class Names

class names 는 CapWords 방식을 사용해야함

ex)

Class MondayMorning(self):

Package , Module Names

전부 소문자만 사용해야 함

Function, Variable Names

전부 소문자만 사용해야 함

Constants

전부 대문자만 사용해야 함

ex)

MAX_ITERATIONS

전반적인 추천

not 사용하지 않기

# Correct:
if foo is not None:

# Wrong:
if not foo is None:

lambda 사용하지 않기

# Correct:
def f(x): return 2*x

# Wrong:
f = lambda x: 2*x

if문 사용할 때, else문 사용해주기

# 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)

slicing 대신 ''.startswith() , ''.endswith() 사용하기

# Correct:
if foo.startswith('bar'):

# Wrong:
if foo[:3] == 'bar':

type() 대신에 isinstance()사용

# Correct:
if isinstance(obj, int):

# Wrong:
if type(obj) is type(1):

boolean 변수에는 == 사용하지 말기

# Correct:
if greeting:

# Wrong:
if greeting == True:


Uploaded by N2T

728x90

'DL&ML' 카테고리의 다른 글

Faiss.indexIVFFlat 설명 및 코드,실험 결과  (1) 2022.11.03
Euclidean(L2 distance) to Cosine similarity Conversion  (0) 2022.11.02
Hardcluster (On Mitigating Hard Clusters for Face Clustering) 리뷰  (0) 2022.10.28
python code 자동정렬  (0) 2022.10.27
code-server에서 원하는 디렉토리 열기  (0) 2022.10.26
    'DL&ML' 카테고리의 다른 글
    • Faiss.indexIVFFlat 설명 및 코드,실험 결과
    • Euclidean(L2 distance) to Cosine similarity Conversion
    • Hardcluster (On Mitigating Hard Clusters for Face Clustering) 리뷰
    • python code 자동정렬
    kongsberg
    kongsberg

    티스토리툴바