Pyright: Incorrect `Unnecessary isinstance call` for Union with mongoengine Document subclasses.

Created on 28 May 2020  路  4Comments  路  Source: microsoft/pyright

Describe the bug
__Incorrect__ Unnecessary isinstance call when working with Union containing mongoengine Document.

To Reproduce
Steps to reproduce the behavior.

Small code snippet below to reproduce the bug.

import random
from typing import Union

from mongoengine import Document
from mongoengine import StringField


class DbModel(Document):
    bar = StringField()


def foo() -> Union[int, DbModel]:
    p = random.random() < 0.5
    return DbModel() if p else 42


isinstance(foo(), int)

error report:

Unnecessary isinstance call; "int | DbModel" is always instance of "int"Pyright (reportUnnecessaryIsInstance)

Expected behavior
isinstance is not unnecessary. I believe that this bug comes from the missing stub files in __mongoengine__. However, it shouldn't be reported as unnecessary.

Screenshots or Code

code snippet above

Additional context
Platform:

  • Python 3.7.6
  • pyright as a VS Code extension 1.1.39
  • mongoengine 0.18.2

Pyright settings in settings.json:

{
  ...
  "pyright.useLibraryCodeForTypes": true,
  "pyright.typeCheckingMode": "strict",
  ...
}
addressed in next version bug

All 4 comments

Thanks for the report.

A couple of follow-up questions for you:

  1. Do you have a type stub for mongoengine?
  2. If you hover over "Document", what type is displayed in the hover text?

I think what's happening here is that the type for Document is unknown, and the logic for determining whether isinstance is unnecessary relies on having complete types. Normally, reportUnneccessaryIsInstance is used in conjunction with "strict" mode where all types are known.

Thank you for reaching out so quickly!

  1. I do not have a type stub for mongoengine. (Pyright reports: Stub file not found for "mongoengine")
  2. If I hover over Document, it displays the type properly I guess:
class Document

The base class used for defining the structure and properties of collections of documents stored in MongoDB.... and so on

I guess, that the lack of a stub file is causing the problem here.

Thanks for the bug report. This will be fixed in the next version of pyright.

This is now fixed in Pyright 1.1.40, which I just published.

Was this page helpful?
0 / 5 - 0 ratings