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

标签 python validation user-input assert

<分区>

在 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 指令下方表示)并返回它的“替换”。在我们的例子中,这个替换在循环中调用原始函数,并捕获这样做时发生的任何异常。如果没有异常发生,它只返回原始函数的结果。

关于python - 进行输入验证的大多数 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20540274/

相关文章:

python - Pandas 数据帧 : split multiple columns into multiple columns

python - Django 计算特定用户对日期时间字段中的日期的访问次数

python - 将bmp转换为tiff,python

c# - 如何使 ViewModel 验证与模型验证保持同步?

java - 为什么错误 "file.too.large"没有在 jsp 中显示(正确)?

linux - 如何从 expect 脚本中传递的 shell 'read' 命令返回?

java - 用户输入创建对象

java - 打印输出直到按下按键

python - 在 Tensorboard 中显示更多图像 - Tensorflow 对象检测

php - 通过超链接单击重新加载页面后保留表单值