在 Python 中进行用户输入验证的最“正确”、Pythonic 方式是什么?
我一直在使用以下内容:
while True:
stuff = input("Please enter foo: ")
try:
some_test(stuff)
print("Thanks.")
break
except SomeException:
print("Invalid input.")
我想这很好而且可读,但我不禁想知道是否没有一些内置函数或我应该使用的东西。
我喜欢装饰器将检查与其余的输入处理分开。
#!/usr/bin/env python
def repeatOnError(*exceptions):
def checking(function):
def checked(*args, **kwargs):
while True:
try:
result = function(*args, **kwargs)
except exceptions as problem:
print "There was a problem with the input:"
print problem.__class__.__name__
print problem
print "Please repeat!"
else:
return result
return checked
return checking
@repeatOnError(ValueError)
def getNumberOfIterations():
return int(raw_input("Please enter the number of iterations: "))
iterationCounter = getNumberOfIterations()
print "You have chosen", iterationCounter, "iterations."
编辑:
装饰器或多或少是现有函数(或方法)的包装器。它采用现有函数(在其@decorator
指令下方表示)并返回它的“替换”。在我们的例子中,这个替换在循环中调用原始函数,并捕获这样做时发生的任何异常。如果没有异常发生,它只返回原始函数的结果。