考虑以下模型定义和用法:
from django.db import models
class User(models.Model):
name: str = models.CharField(max_length=100)
def do_stuff(user: User) -> None:
# accessing existing field
print(user.name.strip())
# accessing existing field with a wrong operation: will fail at runtime
print(user.name + 1)
# acessing nonexistent field: will fail at runtime
print(user.name_abc.strip())
Run Code Online (Sandbox Code Playgroud)
mypy在此基础上运行时,我们将收到以下错误消息user.name + 1:
error: Unsupported operand types for + ("str" and "int")
Run Code Online (Sandbox Code Playgroud)
这可以。但是代码中还有另一个错误- user.name_abc不存在,将在运行时导致AttributeError。
但是,mypy不会看到此信息,因为它允许代码访问任何django属性,并将它们也视为Any:
u = User(name='abc')
reveal_type(user.abcdef)
....
> error: Revealed type is 'Any
Run Code Online (Sandbox Code Playgroud)
那么,如何使mypy看到此类错误?
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |