mypy和django模型:如何检测不存在的属性上的错误 [英] mypy and django models: how to detect errors on nonexistent attributes

查看:32
本文介绍了mypy和django模型:如何检测不存在的属性上的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此模型的定义和用法:

Consider this model definition and usage:

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())

与此同时运行 mypy 时,我们会收到 user.name + 1 的错误:

While running mypy on this, we will get an error for user.name + 1:

error: Unsupported operand types for + ("str" and "int")

这很好.但是代码中还有另一个错误- user.name_abc 不存在,并且会在运行时导致AttributeError.

This is fine. But there's another error in the code - user.name_abc does not exist and will result in AttributeError in runtime.

但是,mypy看不到它,因为它允许代码访问任何django属性,并将它们也视为 Any :

However, mypy will not see this because it lets the code access any django attributes, also treating them as Any:

u = User(name='abc')
reveal_type(user.abcdef)
....

> error: Revealed type is 'Any

那么,如何使mypy看到此类错误?

So, how do I make mypy see such errors?

推荐答案

标志-check-untyped-defs (或-strict )报告缺少属性.已使用 mypy 0.740 版本进行检查.我假设您使用的是 django-stubs 插件.

The flag --check-untyped-defs (or --strict) reports missing attributes. Checked with mypy version 0.740. I assume you are using django-stubs plugin.

这篇关于mypy和django模型:如何检测不存在的属性上的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆