这个问题在这里已经有了答案:
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 建议是什么,以便我们希望开发人员确保他们提供正确的参数,或者我们是否应该添加一些基本验证?
最佳答案
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/