python - python method argument assertions
问题描述
# function that prints hello your name is x and you are y years old
# name must be of type string and cannot be empty
# age must be of type int and cannot be 0
def functionX(name, age):
if name == "":
raise ValueError("name cannot be empty")
if not isinstance(name, str):
raise TypeError("name seem not to be a string")
if age == 0:
raise ValueError("age cannot be 0 (zero)")
if not isinstance(age, int):
raise TypeError("age needs to be an integer")
print("hello ", name, ", you seem to be ", age," years old")
Is this a correct way of checking parameters provided to a function?
解决方案
使代码“更干净” - 添加类型提示并使用 f 字符串。使用mypy之类的类型检查器将验证函数调用者是否传递了一个字符串和一个 int。
def say_hello(name: str, age: int) -> None:
if not isinstance(name, str):
raise TypeError("name seem not to be a string")
if not name:
raise ValueError("name cannot be empty")
if not isinstance(age, int):
raise ValueError("age needs to be an integer")
if age == 0:
raise ValueError("age cannot be 0 (zero)")
print(f'Hello {name} you seem to be {age} years old')
say_hello('jack', 12)
推荐阅读
- apache-spark - Spark RDD 以独占方式按键分区
- python - 如何在熊猫数据框中查找连续相同字符串值的计数?
- python - 如何判断我的 Python 包是否使用 C 扩展?
- stata - 如何以编程方式创建宏的名称并将其用作宏?
- python - 使用 Python 中的第二列按字母顺序排列文本文件
- ios - 编辑 Swift 4 时 TextField 消失
- python - Python Scrapy - 无法登录网站
- angularjs - AngularJs ng-repeat 有条件地按限制过滤
- reactjs - 如何在特定时间后取消 axios 调用
- javascript - Javascript 中奖百分比算法