sbdchd / django-types

:doughnut: Type stubs for Django
MIT License
188 stars 62 forks source link

TypeError: type 'CharField' is not subscriptable #150

Closed adonig closed 1 year ago

adonig commented 1 year ago

I was trying to reproduce the setup from a DjangoCon 2022 talk about type checking Django with pyright and django-types.

At around minute 26:16 you can see some code where a CharField gets subscripted with a literal string type.

For some strange reason that code causes a TypeError when I run python manage.py runserver complaining that the type CharField is not subscriptable.

I thought, maybe I have to install django-types directly from GitHub instead of pip but it didn't work either. Does anyone maybe have a hint what I have to do to make it work?

sbdchd commented 1 year ago

are you monkey patching Django to allow for the indexing?

# in settings.py
from django.db.models import ForeignKey
from django.db.models.manager import BaseManager
from django.db.models.query import QuerySet

# NOTE: there are probably other items you'll need to monkey patch depending on
# your version.
for cls in [QuerySet, BaseManager, ForeignKey]:
    cls.__class_getitem__ = classmethod(lambda cls, *args, **kwargs: cls)  # type: ignore [attr-defined]
adonig commented 1 year ago

@sbdchd I thought it's not necessary because I run Django 4.1.5 and the documentation says:

You'll need to monkey patch Django's QuerySet, Manager (not needed for Django 3.1+) and ForeignKey (not needed for Django 4.1+) classes so we can index into them with a generic argument. Add this to your settings.py:

Just to make sure I put the monkeypatch in my settings.py and sadly the error doesn't go away:

image

sbdchd commented 1 year ago

Oh I didn't have all the classes in the snippet, if you include CharField (or it's parent class maybe?) does it work?

adonig commented 1 year ago

Yes, that works. Thank you. Now I get what that note in the monkey-patch snippet means.

NOTE: there are probably other items you'll need to monkey patch depending on your version

Is there a list of things that generally make sense to get monkey-patched?

sbdchd commented 1 year ago

I basically only monkey patch when something explodes at runtime

I think you can avoid it for most things, but the ORM needs a decent amount of it unfortunately