假设我有一个简单的方法,需要一个字符串列表。
def make_fruits_lower_case(list_of_fruits):
"""make fruits pretty bla bla bla"""
return [fruit.lower() for fruit in list_of_fruits]
Run Code Online (Sandbox Code Playgroud)
用例 1:开发人员提供了一份水果列表,效果很好。预期行为。
make_fruits_lower_case(['APPLE', 'ORANGE']) -- > ['apple', 'orange']
Run Code Online (Sandbox Code Playgroud)
用例 2:假设其他开发人员有意或无意地向其提供了一个字符串。
make_fruits_lower_case('APPLE') --> ['a', 'p', 'p', 'l', 'e']
Run Code Online (Sandbox Code Playgroud)
处理这种情况的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')
Run Code Online (Sandbox Code Playgroud)
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')
Run Code Online (Sandbox Code Playgroud)
但为了清楚地表明您的函数接受列表,您可以指定所需的输入参数的类型(以及期望的输出类型):
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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1997 次 |
| 最近记录: |