Python Enum

2023. 5. 2. 15:54Python is Free/Fluent Python

파이썬 기본 내장으로 Enum이라는 모듈이 있습니다.

오늘은 이 모듈의 필요성과 사용법을 간단히 알아보죠.

Enum을 사용했을 때 장점은 가독성, 유지보수 용이, 코드 안전성, 디버깅 정도가 있겠습니다.

가독성

상수값에 의미 있는 이름을 붙이면, 값을 하드코딩하는 경우보다 가독성이 높습니다.

# Without enums
def apply_discount(price, discount_type):
    if discount_type == 1:
        return price * 0.9
    elif discount_type == 2:
        return price * 0.8

# With enums
from enum import Enum

class DiscountType(Enum):
    TEN_PERCENT = 1
    TWENTY_PERCENT = 2

def apply_discount(price, discount_type):
    if discount_type == DiscountType.TEN_PERCENT:
        return price * 0.9
    elif discount_type == DiscountType.TWENTY_PERCENT:
        return price * 0.8

 

위 코드에서 Enum을 활용한 결과와 그렇지 않았을 때 결과를 보여줍니다.

바로 함수를 정의하는 전자의 구현방식은 discount_type의 값이 1일 때와 2일 때,
각각 어떤 의미를 지니는지 직관적으로 알기 힘듭니다.

유지보수

# Without enums
HTTP_STATUS_OK = 200
HTTP_STATUS_BAD_REQUEST = 400
HTTP_STATUS_NOT_FOUND = 404

# With enums
class HttpStatus(Enum):
    OK = 200
    BAD_REQUEST = 400
    NOT_FOUND = 404

규약상, 오류에 대응하는 숫자값이 별로 바뀔 일이 없다는 점에서
조금 부적절한? 예시 같기도 합니다.

오류 발생 시 반환해야 하는 값이 변경되는 경우,
Enum을 사용하면, 코드의 각 인스턴스가 아니라
Enum에서 정의하는 방식만 바꿔주어도 됩니다.

코드 안전성

코드의 input값에 이상한 값이 입력될 경우, 버그를 방지하는 데 도움을 줄 수 있습니다.

# Without enums
def set_status(status):
    if status not in [1, 2, 3]:
        raise ValueError("Invalid status")

# With enums
class Status(Enum):
    ACTIVE = 1
    INACTIVE = 2
    SUSPENDED = 3

def set_status(status):
    if status not in Status:
        raise ValueError("Invalid status")


디버깅

가독성과 매우 유사한 장점입니다.

파이썬 개발자 분들은 통상 협업(?) 하시겠지만, 
디버깅은 저처럼 본인이 짠 코드도 까먹거나 오류 내는 상황을 겪는
초심자 개발자에게도 특히 더 유용할 것 같아요.

# Without enums
def process_event(event_type):
    if event_type == 1:
        print("Processing event type 1")
    elif event_type == 2:
        print("Processing event type 2")

# With enums
class EventType(Enum):
    LOGIN = 1
    LOGOUT = 2

def process_event(event_type):
    if event_type == EventType.LOGIN:
        print("Processing login event")
    elif event_type == EventType.LOGOUT:
        print("Processing logout event")

위 코드는 로그인, 로그아웃 등으로 인한 오류상황을 명시하고 있습니다.


오늘도 글 읽어주셔서 고맙습니다.

기쁜 하루되세요.