首页 > 解决方案 > 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?

标签: python

解决方案


使代码“更干净” - 添加类型提示并使用 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)

推荐阅读