类型提示是比断言更安全的类型检查选项吗?
Are type hints a safer type checking option than assert?
我有 2 个代码段来检查函数参数的数据类型。
第一个使用打字
def write_str(str1: str, file1_str: str):
return None
第 2 个使用 assert
。
def write_str(str1, file1_str):
assert (type(str1) == str and type(file1_str) == str)
return None
python 键入是否不需要使用断言检查?哪个代码段更容易捕获错误?
我正在使用 python v3.7
注解方法(1st)在传错类型时不会抛出错误。
因此第二种方法更好,但仍有改进的余地:
def write_str(str1, file1_str):
assert (isinstance(str1, str) and isinstance(file1_str, str))
return None
如果您传递从 str
继承的对象,这也将起作用。虽然在这里并不真正相关,但通常建议 isinstance
而不是 type
。
来自PEP 3107, Fundamentals of Function Annotations, p. 2:
By itself, Python does not attach any particular meaning or
significance to annotations. Left to its own, Python simply makes
these expressions available as described in Accessing Function
Annotations below.
注释对可怜的 python 没有任何作用,但它们被其他 python 的官方项目 mypy 使用。
Mypy is an optional static type checker for Python. You can add type
hints (PEP 484) to your Python programs, and use mypy to type check
them statically. Find bugs in your programs without even running them!
简而言之,它是一个 CLI,当类型不匹配时,它会在没有 运行 和 returns 错误列表的情况下解析您的代码。此工具的主要目标是提高代码质量,通常与 other quality control tools like linters and formatters.
一起使用
我有 2 个代码段来检查函数参数的数据类型。
第一个使用打字
def write_str(str1: str, file1_str: str):
return None
第 2 个使用 assert
。
def write_str(str1, file1_str):
assert (type(str1) == str and type(file1_str) == str)
return None
python 键入是否不需要使用断言检查?哪个代码段更容易捕获错误?
我正在使用 python v3.7
注解方法(1st)在传错类型时不会抛出错误。
因此第二种方法更好,但仍有改进的余地:
def write_str(str1, file1_str):
assert (isinstance(str1, str) and isinstance(file1_str, str))
return None
如果您传递从 str
继承的对象,这也将起作用。虽然在这里并不真正相关,但通常建议 isinstance
而不是 type
。
来自PEP 3107, Fundamentals of Function Annotations, p. 2:
By itself, Python does not attach any particular meaning or significance to annotations. Left to its own, Python simply makes these expressions available as described in Accessing Function Annotations below.
注释对可怜的 python 没有任何作用,但它们被其他 python 的官方项目 mypy 使用。
Mypy is an optional static type checker for Python. You can add type hints (PEP 484) to your Python programs, and use mypy to type check them statically. Find bugs in your programs without even running them!
简而言之,它是一个 CLI,当类型不匹配时,它会在没有 运行 和 returns 错误列表的情况下解析您的代码。此工具的主要目标是提高代码质量,通常与 other quality control tools like linters and formatters.
一起使用