最Pythonic的方法来进行输入验证 [英] Most Pythonic way to do input validation
问题描述
在Python中进行用户输入验证的最正确"的Pythonic方法是什么?
What is the most "correct", Pythonic way to do user input validation in Python?
我一直在使用以下内容:
I've been using the following:
while True:
stuff = input("Please enter foo: ")
try:
some_test(stuff)
print("Thanks.")
break
except SomeException:
print("Invalid input.")
我想这很好而且可读性很好,但是我不禁要问是否没有内置函数或应该使用的内置函数.
Which is nice and readable, I suppose, but I can't help wondering if there isn't some built-in function or something I should be using instead.
推荐答案
我喜欢装饰器,以将检查与其余输入处理分开.
I like decorators to separate the checking from the rest of the input handling.
#!/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
指令下方表示),并为其返回替换".在我们的案例中,此替换在循环中调用原始函数,并捕获在此过程中发生的任何异常.如果没有异常发生,则只返回原始函数的结果.
A decorator is more or less a wrapper for an existing function (or method). It takes the existing function (denoted below its @decorator
directive) and returns a "replacement" for it. This replacement in our case calls the original function in a loop and catches any exception happening while doing so. If no exception happens, it just returns the result of the original function.
这篇关于最Pythonic的方法来进行输入验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!