Decorator를 활용한 Depreciated Function 관리 전략

Decorator를 활용한 Depreciated Function 관리 전략
Photo by vadim kaipov / Unsplash

Code

import warnings  
import functools  
  
def deprecated(reason=None, alternative=None):  
    """  
    Deprecated Function을 표시하는 데코레이터입니다.  
        Args:  
        reason (str, optional): 함수가 Deprecated 된 이유를 설명합니다.  
        alternative (str, optional): 대체 함수나 방법을 안내합니다.  
    """    def decorator(func):  
        @functools.wraps(func)  
        def wrapped(*args, **kwargs):  
            message = f"Warning: {func.__name__}() is deprecated"  
            if reason:  
                message += f" because {reason}."  
            else:  
                message += "."  
  
            if alternative:  
                message += f" Consider using {alternative} instead."            warnings.warn(message, category=DeprecationWarning, stacklevel=2)  
            return func(*args, **kwargs)  
          
        return wrapped  
      
    return decorator  
  
# 예제 사용  
@deprecated(reason="This function is too slow", alternative="new_function")  
def old_function(x, y):  
    return x + y  
  
def new_function(x, y):  
    return x + y + 1  # 대체 함수의 간단한 예시  
  
# 함수 호출  
result = old_function(3, 4)
/var/folders/5l/qwrwf4qs1f9d4bbwq0wh80s00000gn/T/ipykernel_40378/4140994627.py:40: DeprecationWarning: Warning: old_function() is deprecated because This function is too slow. Consider using new_function instead.
  result = old_function(3, 4)