Python coding convention

2020. 2. 25. 17:27IT관련

반응형

Python PEP8

모든 프로그래밍 언어가 그렇듯 python도 conding cenvention이 존재한다.

당연히 이대로 코딩을 한다면 좋다는 의미이다.

 

들여쓰기

Space 4칸으로 지정한다. 참고로 나는 절대로 tab을 사용하지 않는다. Space와 tab을 혼용해서 사용해서는 안된다.

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

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

# Hanging indents should add a level.
foo = long_function_name(
    var_one, var_two,
    var_three, var_four)

 

한 라인 최대 글자수

최대 79자. 이건 개인 취향인듯 싶다.

긴 조건문의 경우 back slash로 나누기도 한다는데, 굳이 이럴 필요는 없을 듯 싶다.

 

빈줄

함수와 클래스 사이는 빈줄 2개로 구분짓는다. 다만 클래스 내부 함수는 빈줄 1개로 구분한다.

 

Imports

한줄에 하나씩 import한다. 

Yes: import os
     import sys

No:  import sys, os

 

문자열 따옴표

왜 python은 문자열을 정의하는 기호를 하나로 정해두지 않은 건지 답답하다. 

개인적으로 일반적인 프로그래밍 언어와 동일하게 "으로 지정하는게 좋을 것 같다.

 

표현식, 조건식의 공백

Yes: spam(ham[1], {eggs: 2})
No:  spam( ham[ 1 ], { eggs: 2 } )
Yes: foo = (0,)
No:  bar = (0, )
Yes: if x == 4: print x, y; x, y = y, x
No:  if x == 4 : print x , y ; x , y = y , x
Yes:
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]

No:
ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : upper]
ham[ : upper]
Yes: spam(1)
No:  spam (1)
Yes: dct['key'] = lst[index]
No:  dct ['key'] = lst [index]
Yes:
x = 1
y = 2
long_variable = 3

No: 
x             = 1
y             = 2
long_variable = 3

위 내용은 좀 의아했다. 

 

주석(#)

코드와 같은 레벨의 들여쓰기에 맞춰야 한다. 또한 # 다음 한칸의 스페이스가 있어야 한다.

인라인 주석의 경우 스페이스 2개 후 추가한다.

 

"""Return a foobang

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

 

Naming conventions

Python naming conventions

 

참고

Google python style guides: http://google.github.io/styleguide/pyguide.html

 

styleguide

Style guides for Google-originated open-source projects

google.github.io

 

반응형

'IT관련' 카테고리의 다른 글

새로운 Nest Aware 요금제  (4) 2020.07.02
특정경로에 있는 package를 runtime시 import 하기  (0) 2020.05.20
IC package type  (0) 2020.02.05
신뢰성 테스트  (2) 2019.03.19
Requests: HTTP for Humans (1)  (0) 2018.11.30