【发布时间】:2018-02-28 21:11:58
【问题描述】:
我需要实现很多这样的案例选择功能:
def foo1(bar1):
if bar1 == 'A':
do something
elif bar1 == 'B':
do something
elif ...
...
else:
raise ValueError('legal input of bar1 should be {}'.format(list_of_bar))
def foo2(bar2):
if bar2 == 'A':
do something
elif bar2 == 'B':
do something
elif ...
...
else:
raise ValueError('legal input of bar2 should be {}'.format(list_of_bar))
'''
根据“不要自己重复”,有没有办法避免重复引发错误的最后一步并打印正确参数的列表?我认为装饰师可能会这样做,但不知道如何制作。提前致谢。
更新
我自己用检查模块实现了它。但我还是希望能得到一些建议或更好的解决方案
import inspect
from functools import wraps
import re
def test_none(func):
_code = inspect.getsource(func)
_list = re.findall(r'if (\w+) == (\w+)', _code)
assert all(_list[0][0] == name for name, case in _list)
_arg = _list[0][0]
_case = tuple(case for name, case in _list)
@wraps(func)
def wrapper(*args, **kwargs):
results = func(*args, **kwargs)
if results is None:
raise ValueError(
'Legal value of \'{arg}\' should be anyone of {case}'.format(
arg=_arg, case=_case))
return results
return wrapper
@test_none
def foo(bar):
if bar == 0:
return 1
elif bar == 1:
return 2
测试示例:
foo(3)
ValueError: Legal value of 'bar' should be anyone of ('0', '1')
【问题讨论】:
-
您正在寻找将
"A"映射到do something、"B"到do something else等的东西。换句话说,您想要一个字典。 -
但是有了字典,我还需要做最后的 raise Error 和打印步骤,这是我真的想通过装饰器或其他“黑魔法”来避免。
标签: python metaprogramming decorator