#30019 closed New feature (needsinfo)
Add __class_getitem__ method to managers and querysets
| Reported by: | Maxim Kurnikov | Owned by: | Greg W |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | dev |
| Severity: | Normal | Keywords: | |
| Cc: | Herbert Fortes | Triage Stage: | Unreviewed |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | yes | UI/UX: | no |
Description
I'm working on a pep561 stubs package for Django here
https://github.com/mkurnikov/django-stubs
In order to be able to fully support managers as a generics, one needs to write
from django.db import models
class UserManager(models.Manager[User]):
def get_or_404(self) -> User:
pass
class User(models.Model):
objects = UserManager()
but it fails at models.Manager[User] .
There's a new method __class_getitem__ in python3.7 to get around that, defined in pep560
https://www.python.org/dev/peps/pep-0560/
Change History (7)
comment:1 by , 7 years ago
| Owner: | changed from to |
|---|---|
| Status: | new → assigned |
comment:2 by , 7 years ago
comment:3 by , 7 years ago
TypeError: 'type' object is not subscriptable
Look at
https://www.python.org/dev/peps/pep-0560/#class-getitem
and how it was implemented before with GenericMeta
https://www.python.org/dev/peps/pep-0484/#user-defined-generic-types
Minimal repro should be this one
from django.db import models
class UserManager(models.Manager['User']):
pass
class User(models.Model):
objects = UserManager()
comment:4 by , 7 years ago
| Cc: | added |
|---|
comment:5 by , 7 years ago
I got __class_getitem__ implemented. However, I am having an issue with models.Manager['User']
Isn't 'User' just a string which __class_getitem__ would not be valid on? I think the idea is to index the class User, but this class has not been defined prior to Manager[User].
Let me know if I am off base.
comment:6 by , 7 years ago
| Resolution: | → needsinfo |
|---|---|
| Status: | assigned → closed |
Hi Maxim.
I'm going to close this as needsinfo right now. Not because I'm against it but because it's part of the wider discussion around Type Hinting in Django.
I see you posted to the Django-Developers thread about this: https://groups.google.com/d/topic/django-developers/trTEbURFhEY/discussion
Can I ask you to add your effort there? I think there's a group of people who are there or there-abouts with this: as ever, it just needs a bit of a nudge.
(There was talk of a DEP, of a working groups, of... — we just need to get there.)
Thanks.
I'll post there to try and re-liven it.
comment:7 by , 7 years ago
(And #29299 is the Someday/Maybe ticket for adding type hints and variable annotations.)
Is this the error you are getting:
NameError: name 'User' is not defined
If not, can you please let me know what the error is?