当你不知道如何准确地描述这个问题时,很难找到答案…
处理一组相当深(但固定)的嵌套测试,最惯用的方法是什么?这些测试希望按顺序运行,但在第一组测试成功后立即终止?
而不是以下内容
选项1:
(导致压痕过多)
def make_decision():
results = ... some code or function that returns a list or None
if results:
decision = random.choice(results)
else:
results = ... other code or function
if results:
decision = random.choice(results)
else:
results = ... other code or function
if results:
decision = random.choice(results)
else:
results = ... other code or function
if results:
decision = random.choice(results)
...etc.
else:
decision = None
print(decision)
return decision
选项2
另一种选择是尽早从函数返回,但我不确定分散有这么多返回是一种好的做法,在这种情况下,我宁愿在最后做一件事(例如
print(decision)
)返回前:
def make_decision():
results = ... some code or function that returns a list or None
if results:
return random.choice(results)
results = ... other code or function
if results:
return random.choice(results)
results = ... other code or function
if results:
return random.choice(results)
...etc.
else:
decision = None
return decision
选项3
最后,我可以使每个测试成为一个单独的函数
as described here
并且迭代地调用它们,前提是每个测试函数都有相同的参数集。
def test1(args):
...
def test2(args):
...
def test3(args):
...
def make_decision():
decision = None
for test in [test1, test2, test3, ...]:
results = test(args)
if results:
decision = random.choice(results)
break
print(decision)
return decision
这看起来是最好的,但我没有计划为每个测试都创建一个函数,有些测试可以用相同的函数完成,但是使用不同的参数,有些只是一行代码,而另一些是多行代码。那么,在开始循环之前,我需要构建一个函数和参数列表吗?或者列出
partial
功能?
欢迎提出更好的建议(在我继续执行上述选项3之前)
更新2018-07-21:
未来的潜在选择
我不知道我在和这个问题搏斗,
PEP 572
得到了批准(范罗森因此辞职)。如果实施了该政治公众人物计划,我认为还可以采用以下解决方案:
def make_decision():
if (results := ... some code or function) is not None:
decision = random.choice(results)
elif (results := ... some code or function) is not None:
decision = random.choice(results)
...etc.
else:
decision = None
return decision