大多数Pythonic方式进行输入验证

hen*_*tha 6 python validation assert user-input

在Python中进行用户输入验证的最"正确"Pythonic方法是什么?

我一直在使用以下内容:

while True:
    stuff = input("Please enter foo: ")
    try:
        some_test(stuff)
        print("Thanks.")
        break
    except SomeException:
        print("Invalid input.")
Run Code Online (Sandbox Code Playgroud)

我想,这是好的和可读的,但我不禁想知道是否有一些内置函数或我应该使用的东西.

Alf*_*lfe 8

我喜欢装饰器将检查与输入处理的其余部分分开.

#!/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."
Run Code Online (Sandbox Code Playgroud)

编辑:

装饰器或多或少是现有函数(或方法)的包装器.它采用现有函数(在其@decorator指令下面表示)并为其返回"替换".在我们的情况下,这个替换在循环中调用原始函数并捕获发生的任何异常.如果没有异常发生,它只返回原始函数的结果.

  • 我为代码添加了一个小解释,但当然,这里解释装饰器的范围是不合适的.Stackoverflow上有很多关于该主题的问题. (2认同)