typeddjango / django-stubs

PEP-484 stubs for Django
MIT License
1.57k stars 435 forks source link

Unable to subclass HttpRequest to override type of User #407

Closed bullfest closed 4 years ago

bullfest commented 4 years ago

I'd like to create a AuthenticatedHttpRequest to indicate that a user has been authenticated (for example to annotate the request parameter for views with the login_required decorator).

I'd expect this to be done like so:

class AuthenticatedHttpRequest(HttpRequest):
    user: User

The problem is that the type of user is changed by this transformer https://github.com/typeddjango/django-stubs/blob/574a87e68cfb2e6ff66b3d7e1a0bb75f51148a8c/mypy_django_plugin/transformers/request.py#L10-L26 That's called here https://github.com/typeddjango/django-stubs/blob/574a87e68cfb2e6ff66b3d7e1a0bb75f51148a8c/mypy_django_plugin/main.py#L244-L245

rendering it somewhat impossible to declare these kinds of subclasses.


Not sure what a solution would be here.

Only changing the type of user if the object it's accessed on is an instance of HttpRequest (not for subclasses) would possibly be a solution, but would require that all HttpRequest-subclasses declare the type of user to not fall back to the imprecise type annotations in the .pyi file.

Would it be possible to check the type and only change it if it's what's expected from the .pyi-file (Union[AbstractBaseUser, AnonymousUser])?

bullfest commented 4 years ago

We should probably also update the readme and remove/update this section: https://github.com/typeddjango/django-stubs#how-can-i-use-httprequest-with-custom-user-model

sobolevn commented 4 years ago

This is a critical bug, because without custom user models - these stubs do not make much sense.

sobolevn commented 4 years ago

@kszmigiel can you please have a look?

kszmigiel commented 4 years ago

@sobolevn Sure thing, as soon as I solve dining philosophers problem for Uni 😝

bullfest commented 4 years ago

This is a critical bug, because without custom user models - these stubs do not make much sense.

Custom user models work fine (the type becomes Union[<custom user model>, AnonymousUser]), it's just that creating subclasses of HttpRequest with only authenticated users doesn't work.

I'd say it's important but it's not critical, more a quality of life thing to avoid having to have non-needed asserts/if-statements.

In regards to the readme the mentioned section should probably be removed as the problem that it answers just works™ with the mypy-plugin (thus becoming a red herring when debugging).

sobolevn commented 4 years ago

Oh, I see. This indeed is not critical.

But, we still need to fix that as well. Can you please post the output from mypy?