Closed
Description
Continuing the discussion started at #1649 (comment)
There are two similar use cases affected by two different PRs:
- Fix crash when constructing an abstract model with recursive relation #1393
- Move ModelBase.objects declaration to Model.objects, for mypy 1.5.0 #1649
Since the changes in #1393, django-stubs will raise errors on some kinds of generic code that handles abstract models. For example:
# models.py
from typing import TypeVar
from django.db import models
from django_stubs_ext.db.models import TypedModelMeta
class Animal(models.Model):
name = models.CharField(max_length=100)
class Meta(TypedModelMeta):
abstract = True
class Cat(Animal): # Concrete model
pass
def create_animal(klass: type[Animal], name: str) -> Animal:
obj = klass(name=name)
obj.save()
return obj
T = TypeVar("T", bound=Animal)
def create_animal_generic(klass: type[T], name: str) -> T:
return klass.objects.create(name=name)
# Usage example:
# create_animal(Cat, "Garfield")
# create_animal_generic(Cat, "Grumpy")
These two functions are allowed and work with django-stubs 4.2.3. Function create_animal
causes errors in git master version of django-stubs:
apidoc/models.py:16:11: error: Cannot instantiate abstract model "Animal" [misc]
But after the unmerged changes in PR #1649, the second function create_animal_generic
will also start failing:
models.py:16:11: error: Cannot instantiate abstract model "Animal" [misc]
models.py:23:12: error: Cannot instantiate abstract model "Animal" [misc]
models.py:23:12: error: Incompatible return value type (got "Animal", expected "T") [return-value]
System information
python
version: 3.11.4mypy
version: 1.4.1django-stubs
version: 4.2.3 / git