mypy and django models: how to detect errors on nonexistent attributes

空扰寡人 提交于 2019-12-07 06:45:38

问题


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

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

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

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

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

So, how do I make mypy see such errors?


回答1:


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



来源:https://stackoverflow.com/questions/53370377/mypy-and-django-models-how-to-detect-errors-on-nonexistent-attributes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!