typeddjango / django-stubs

PEP-484 stubs for Django
MIT License
1.61k stars 452 forks source link

`ContentType.app_label` is typed as `Any` by mypy #2446

Open mthuurne opened 3 days ago

mthuurne commented 3 days ago

Bug report

What's wrong

If I run mypy on this code:

from django.contrib.contenttypes.models import ContentType
from django.db import models

def f(model: type[models.Model]) -> None:
    ct = ContentType.objects.get_for_model(model)
    reveal_type(ct)
    reveal_type(ct.app_label)

It outputs:

testcase.py:6: note: Revealed type is "django.contrib.contenttypes.models.ContentType"
testcase.py:7: note: Revealed type is "Any"

In django-stubs/contrib/contenttypes/models.pyi, the ContentType class is annotated as follows:

class ContentType(models.Model):
    id: int
    app_label: models.CharField
    # (snip)

So the type for ct is inferred as expected, but for the app_label field it is not, even though that field is annotated in the stubs. Is this some bug or limitation of the plugin?

How is that should be

The runtime type for ct.app_label is str, so ideally that would be the inferred type.

System information

sobolevn commented 3 days ago

PR is welcome

mthuurne commented 3 days ago

I could use some hints on where to start looking. Is it expected or unexpected that the type for app_label isn't inferred? And would the solution indeed be to change the plugin?