python - 函数参数验证 : what is the pythonic way?

标签 python

这个问题在这里已经有了答案:





Best way to check function arguments? [closed]

(14 个回答)



Parameter validation, Best practices in Python

(4 个回答)


5 个月前关闭。
社区在 2 个月前审查了是否重新打开这个问题并关闭了它:

原始关闭原因未解决





假设我有一个简单的方法,它需要一个字符串列表。

 def make_fruits_lower_case(list_of_fruits):
    """make fruits pretty bla bla bla"""
    return [fruit.lower() for fruit in list_of_fruits]
用例 1:开发人员提供了一个水果列表,它工作正常。预期行为。
make_fruits_lower_case(['APPLE', 'ORANGE']) -- > ['apple', 'orange']
用例 2:假设某个其他开发人员有意或无意地为其提供了一个字符串。
make_fruits_lower_case('APPLE') --> ['a', 'p', 'p', 'l', 'e']
处理这种情况的pythonic方法是什么?
1:引入参数验证
def make_fruits_lower_case(list_of_fruits):
    if isinstance(list_of_fruits, list):
            return [fruit.lower() for fruit in list_of_fruits]raise 
        TypeError('list_of_fruits must be a of type list')
    
2:期望用例 2 中的开发人员提供列表。
除了这种特定情况之外,很高兴知道一般处理此类情况的 Pythonic 建议是什么,以便我们希望开发人员确保他们提供正确的参数,或者我们是否应该添加一些基本验证?

最佳答案

  • 您的验证错误被认为是 Pythonic:
  • def make_fruits_lower_case(list_of_fruits):
        if isinstance(list_of_fruits, list):
            return [fruit.lower() for fruit in list_of_fruits]
        raise TypeError('list_of_fruits must be a of type list')
    
    但是为了明确您的函数接受列表,您可以指定所需的输入参数类型(以及期望的输出类型):
    def make_fruits_lower_case(list_of_fruits : list) -> list:
        if isinstance(list_of_fruits, list):
            return [fruit.lower() for fruit in list_of_fruits]
        raise TypeError('list_of_fruits must be a of type list')
    

    关于python - 函数参数验证 : what is the pythonic way?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68083900/

    相关文章:

    python - bbfreeze 和 protobuf

    python - 更改 python matplotlib python 图的配色方案

    python - 从另一个 Python 脚本运行 Python 脚本时处理异常

    python - "AttributeError: ' 模块 ' has no attribute ' 播放器 '"尝试使用 Boost::Python 将 python 对象加载到 C++ 中时

    Python-删除项目

    python - 使用装饰器在类内部进行函数包装

    python - Matplotlib 无处不在地绘制未定义的图

    python - 如何保存当前python session 中的所有变量?

    c++ - 如何在python中将结构作为参数发送

    python - 将任意命名的文件导入为 Python 模块,而不生成字节码文件