python 中的模板/通用用户定义 类 怪异行为
Template / Generic user-defined classes in python weird behavior
当我编写以下代码时,mypy 发出错误(它应该如此):
from typing import TypeVar, Generic, List
Data = TypeVar("Data")
class State(Generic[Data]):
def __init__(self) -> None:
self.d: Data = 8.9
s = State[int]()
当我从 ctor 中删除(完全多余,对吗?)-> None
部分时,mypy
忽略 类型不匹配。这是为什么? (请注意,这 不是 this 的副本)
Mypy 只检查输入的函数。通过删除 -> None
你使你的 __init__
无类型,因此 mypy 不检查该函数。
mypy wiki 的常见问题部分对此进行了介绍:https://mypy.readthedocs.io/en/stable/common_issues.html#no-errors-reported-for-obviously-wrong-code
There are several common reasons why obviously wrong code is not flagged as an error.
The function containing the error is not annotated. Functions that do not have any annotations (neither for any argument nor for the return type) are not type-checked, and even the most blatant type errors (e.g. 2 + 'a'
) pass silently. The solution is to add annotations. Where that isn’t possible, functions without annotations can be checked using --check-untyped-defs
.
当我编写以下代码时,mypy 发出错误(它应该如此):
from typing import TypeVar, Generic, List
Data = TypeVar("Data")
class State(Generic[Data]):
def __init__(self) -> None:
self.d: Data = 8.9
s = State[int]()
当我从 ctor 中删除(完全多余,对吗?)-> None
部分时,mypy
忽略 类型不匹配。这是为什么? (请注意,这 不是 this 的副本)
Mypy 只检查输入的函数。通过删除 -> None
你使你的 __init__
无类型,因此 mypy 不检查该函数。
mypy wiki 的常见问题部分对此进行了介绍:https://mypy.readthedocs.io/en/stable/common_issues.html#no-errors-reported-for-obviously-wrong-code
There are several common reasons why obviously wrong code is not flagged as an error.
The function containing the error is not annotated. Functions that do not have any annotations (neither for any argument nor for the return type) are not type-checked, and even the most blatant type errors (e.g.
2 + 'a'
) pass silently. The solution is to add annotations. Where that isn’t possible, functions without annotations can be checked using--check-untyped-defs
.