Pylance "unreachable code" on ModelViewSet's get_queryset and get_object methods (and those using them) #9868
|
Hello, After coming back to a project that uses DRF, after a while, I've noticed that Pylance marks After adding the type annotation |
Replies: 1 comment
|
Your diagnosis holds up. The class attribute carries no annotation at all, so the declared type is inferred purely from the assignment: >>> [l.strip() for l in inspect.getsource(GenericAPIView).splitlines() if l.strip().startswith("queryset")][0]
'queryset = None'
>>> GenericAPIView.__annotations__
{}With DRF doesn't ship inline types or a which declares these attributes properly and stops the false positives across the whole class, not just the two methods you patched. Worth noting they're maintained separately from DRF, so their coverage can lag releases. If you'd rather not add the dependency, subclassing is a bit less invasive than editing site-packages: class BaseViewSet(ModelViewSet):
queryset: QuerySet | None = NoneConfirmed on DRF 3.18.0 / Django 5.2.17. |
Your diagnosis holds up. The class attribute carries no annotation at all, so the declared type is inferred purely from the assignment:
With
querysetinferred asNone,assert self.queryset is not Nonenarrows it toNever, the assert is treated as always failing, and everything after it — includingget_object()— is flagged unreachable. AddingQuerySet | Nonefixes it because it gives the narrowing something to survive into, which is why your workaround works.DRF doesn't ship inline types or a
py.typedmarker, so this isn't …