pyright icon indicating copy to clipboard operation
pyright copied to clipboard

Code unreachable false positive in djagorestframework example

Open figuld opened this issue 1 year ago • 1 comments

Describe the bug Pyright falsely tags code as unreachable in the rest-framework-tutorial example.

Code or Screenshots If possible, provide a minimal, self-contained code sample (surrounded by triple back ticks) to demonstrate the issue. The code should define or import all referenced symbols.

from rest_framework import viewsets
from rest_framework.response import Response

class SnippetViewSet(viewsets.ModelViewSet):
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)  # code unreachable

Have djangorestframework 3.16.0 and django 5.1.8 (same bug with 5.2). I can reproduce the bug by git cloning the repo and analyzing the file.

VS Code extension or command-line Binary /usr/bin/pyright (1.1.400) executed by neovim's lsp.

figuld avatar May 03 '25 20:05 figuld

Pyright is working as designed here, so I don't consider this a bug.

The library in question has no type annotations. I presume you are not using any stubs. That means pyright will attempt to infer the return types as best it can under the circumstances. Type inference works well most of the time, but it can produce results that deviate from the intentions of the library author.

If you're curious, here's why pyright's type inference logic assumes this code is unreachable. The get_object method, which comes from the GenericAPIView class, calls get_queryset. This method contains the statement assert self.queryset is not None, but queryset is assigned only a value of None in the class. That means its type is inferred to be None, and the assert is assumed to always fail, which means the inferred return type of get_queryset is NoReturn. To address this, the library maintainer would need to provide a type annotation for the queryset attribute defining its type as object | None or something such as that. Alternatively, a return type annotation could be aded to get_queryset or get_object to specify that the return type is something other than NoReturn.

Your options are:

  1. Work with the library author to add partial type annotations.
  2. Create type stubs for the library and add partial type information.
  3. Set useLibraryCodeForTypes to false in the pyright configuration. This tells pyright not to attempt to infer return types for untyped libraries.

erictraut avatar May 03 '25 21:05 erictraut