티스토리 뷰

파이썬에서 파라미터로 전달받는 데이터의 값을 제한하기 위해서 데코레이터를 이용하는 방법은 다음과 같다.

파이썬3면 Enum을 이용하면 좀더 깔끔하게 처리할 수 있을 것 같다.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
_LIST1_ = [ "json", "txt", "csv" ]
_LIST2_ = [ "1", "2", "3" ]
_LIST3_ = [ "a", "b", "c" ]
def check_param_values(param_index, check_list):
''' param_index로 전달된 데이터가, check_list에 있는 데이터 인지 확인하고 오류를 발생하는 데코레이터 '''
def wrapper(func):
def decorator(*args, **kwargs):
print("%s %s" % (func.__name__, "before"))
if args[param_index] not in check_list:
raise ValueError("args error {0} not in [{1}]".format(args[param_index], ",".join(check_list)))
print(args)
print(kwargs)
result = func(*args, **kwargs)
print("%s %s" % (func.__name__ , "after"))
return result
return decorator
return wrapper
@check_param_values(0, _LIST1_)
@check_param_values(1, _LIST2_)
@check_param_values(2, _LIST3_)
def func(param1, param2, param3):
return "{0}, {1}, {2}".format(param1, param2, param3)
print func("json", "2", "c")



인스펙트를 이용하여 추가로 처리하는 예제는 다음과 같다.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import inspect

values = [ "a", "b", "c" ]

def check_param_values(param_name, check_list):
    def wrapper(func):
        param_index = inspect.getargspec(func).args.index(param_name)
       
        def decorator(*args, **kwargs):
            if args[param_index] not in check_list:
                raise ValueError("Argument value error {0} not in [{1}]".format(param_name, ", ".join(check_list)))
           
            return func(*args, **kwargs)
        return decorator
    return wrapper

@check_param_values("param1", values)
def temp(param1, param2):
    print(param1, param2)
   
temp("f", "b")

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
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
글 보관함