youtux / types-factory-boy

Type stubs for factory-boy
MIT License
18 stars 4 forks source link

Issue: FactoryMetaClass does not define __getitem__ #53

Open Tsdevendra1 opened 11 months ago

Tsdevendra1 commented 11 months ago

I'm not sure if I'm using this wrong but when I define a factory such as:


class UserFactory(factory.django.DjangoModelFactory[User]):
    class Meta:
        model = User

I get the following error:

Class 'FactoryMetaClass' does not define '__getitem__', so the '[]' operator cannot be used on its instances

I understand why the error occurs, but I'm not sure what the intended solution is. Since DjangoModelFactory is generic in the stubs, what's the intended usage if DjangoModelFactory isn't actually able to support getitem? Should I monkeypatch FactoryMetaClass?

axieum commented 9 months ago

If you're also using typeddjango/django-stubs, a workaround is to piggy-back off of their monkey-patching:

import django_stubs_ext
import factory

# Monkeypatching Django, so stubs will work for all generics, see: https://github.com/typeddjango/django-stubs
django_stubs_ext.monkeypatch(
  extra_classes=[
    # https://github.com/youtux/types-factory-boy/issues/53
    factory.base.BaseFactory,
    factory.declarations.BaseDeclaration,
    factory.declarations.Trait,
    # ...
  ]
)
youtux commented 8 months ago

yeah it looks like this is quite a big limitation, until the upstream (django) will fix their classes to be typed and generic