在Python中进行用户输入验证的最“正确”的Pythonic方法是什么?
我一直在使用以下内容:
while True:
stuff = input("Please enter foo: ")
try:
some_test(stuff)
print("Thanks.")
break
except SomeException:
print("Invalid input.")
我想,这是好的和可读的,但我不禁想知道是否有一些内置函数或我应该使用的东西。
答案 0 :(得分:6)
我喜欢装饰器将检查与输入处理的其余部分分开。
#!/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
指令下面表示)并为其返回“替换”。在我们的情况下,这个替换在循环中调用原始函数并捕获发生的任何异常。如果没有异常发生,它只返回原始函数的结果。
答案 1 :(得分:2)
使用“用户输入”进行此类验证的最 Pythonic 方法是捕获适当的异常。
示例:强>
def get_user_input():
while True:
try:
return int(input("Please enter a number: "))
except ValueError:
print("Invalid input. Please try again!")
n = get_user_input()
print("Thanks! You entered: {0:d}".format(n))
允许异常发生在他们撒谎的位置并允许它们冒泡而不是隐藏它们以便您可以清楚地看到 Python Traceback 中出现的问题也是一种好习惯。
在这种情况下验证用户输入 - 使用Python的 Duck Typing 并捕获错误。即:如果它像管道一样,它必须是一只鸭子。 (如果它像int一样,它必须是一个int )。
答案 2 :(得分:0)
有点复杂,但可能很有趣:
import re
from sys import exc_info,excepthook
from traceback import format_exc
def condition1(stuff):
'''
stuff must be the string of an integer'''
try:
i = int(stuff)
return True
except:
return False
def condition2(stuff):
'''
stuff is the string of an integer
but the integer must be in the range(10,30)'''
return int(stuff) in xrange(10,30)
regx = re.compile('assert *\( *([_a-z\d]+)')
while True:
try:
stuff = raw_input("Please enter foo: ")
assert(condition1(stuff))
assert ( condition2(stuff))
print("Thanks.")
break
except AssertionError:
tbs = format_exc(exc_info()[0])
funky = globals()[regx.search(tbs).group(1)]
excepthook(exc_info()[0], funky.func_doc, None)
结果
Please enter foo: g
AssertionError:
stuff must be the string of an integer
Please enter foo: 170
AssertionError:
stuff is the string of an integer
but the integer must be in the range(10,30)
Please enter foo: 15
Thanks.
我找到了简化方法:
from sys import excepthook
def condition1(stuff):
'''
stuff must be the string of an integer'''
try:
int(stuff)
return True
except:
return False
def another2(stuff):
'''
stuff is the string of an integer
but the integer must be in the range(10,30)'''
return int(stuff) in xrange(10,30)
tup = (condition1,another2)
while True:
try:
stuff = raw_input("Please enter foo: ")
for condition in tup:
assert(condition(stuff))
print("Thanks.")
break
except AssertionError:
excepthook('AssertionError', condition.func_doc, None)