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?