View

TIL 41 | PYTHON_Coding Convention

Melody:) 2021. 8. 19. 09:13

Python Coding Convention 

파이썬 코드 스타일에는 여러가지가 있지만,
대표적인 것은 파이썬 공식 가이드인 PEP-8과 구글의 파이썬 코딩 스타일이 있다.
다음 내용은 >wecode의 파이썬 코딩 스타일 가이드 입니다.

기본적으로는 PEP-8과 일맥상통 하며, wecode만의 스타일과 철학을 추가한 코딩 스타일 가이드 입니다.

중요한것은 가독성.

  • 깔끔한 코딩 스타일
  • 간단하고 명료한 로직
  • 명확한 변수, 함수, 클래스 등의 이름

 

Naming

# 변수 이름 예제
user         = User()
users        = get_users()
bmw          = Car("BMW")
http_request = HttpRequest()
total_cost   = calculate_total_cost()

# Constant(상수)
DEBUG_LEVEL = 1
MAX_USERS   = 200
VIP         = 3

# 함수 이름 예제
def calculate_total_cost():
    # ...

def get_user_permission(user):
   # ...

def buy_stock(stock_name):
   # ...

# 클래스 이름 예제
class User:
    # ...

class HttpRequest:
    # ....

class Car:
    # ...

# 모듈 이름 예제
module.py
my_module.py

# 팩케지 이름 예제
package
mypackage

일반적으로 변수나 클래스는 이름이 명사로 이루어지며 함수는 동사 입니다.

파이썬에서는 클래스는 이름을 대문자로 구분하는 것을 제외하고는  일반적으로 _ 을 사용해서 단어들을 구분합니다. 

또한 상수(constant)는 일반적으로 전부 대문자로 이루어지고 팩케지는 _를 사용해서 구분하지 않습니다.

 

Space

일반적으로 빈 줄은 하나만 삽입 합니다.
(어떤 가이드들은 클래스와 클래스 사이는 2줄의 빈 줄을 삽입하라고 안내하는 가이드도 있지만 저희는 기본적으로 빈 줄은 하나만 사용합니다).

Bad

class User:

    def __init__(self, name):
        self.name



if True:
    print("Hello World!")
    if False:
        print("False")

else:
    print("Else")
 

def create_user(user):
    new_user      = User()

    new_user.name = user["name"]
    new_user.age  = user["age"]        
    save_user(new_user)

try:

    do_something()



except Exception as e:
    print("Exception!!")

Good

class User:
    def __init__(self, name):
        self.name

if True:
    print("Hello World!")

    if False:
        print("False")
else:
    print("Else")
 
def create_user(user):
    new_user      = User()
    new_user.name = user["name"]
    new_user.age  = user["age"]       
 
    save_user(new_user)

try:
    do_something()
except Exception as e:
    print("Exception!!")

 

Code Align

Bad

import django
from something import awesome
from math import random
import requests

new_user = User()
new_user.name = user["name"]
new_user.age = user["age"]
new_user.feature = "?"       

user = { 
    "id" : 1, 
		"name" : "아이유", 
		"age" : 27, 
		"gender" : "Female", 
		"occupation" : "Artist"
}

Good

import django
import requests

from something import awesome
from math      import random

new_user         = User()
new_user.name    = user["name"]
new_user.age     = user["age"]
new_user.feature = "?" 

user = { 
   		"id"         : 1, 
		"name"       : "아이유", 
		"age"        : 27, 
		"gender"     : "Female", 
		"occupation" : "Artist"
}

=> vim은 자동으로 align을 해주는 Align이라는 플러그인이 있습니다.

      vim 을 배워서 사용해봅시다!

Share Link
reply
«   2024/10   »
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