pythonvisual-studio-codepython-typingpython-3.10pyright

Python Analysis: Type Checking Mode in VS CODE


I changed the settings "Python Analysis: Type Checking Mode" to strict mode

enter image description here

And I get an error while checking for an instance of str,

def is_name(name: str) -> bool:
    if isinstance(name, str):
        return True

Unnecessary isinstance call; "str" is always an instance of

enter image description here

Is this a code problem or a settings problem?


Solution

  • This happens because you already annotated the name parameter as str, so it seems silly to narrow the type again after that with isinstance.

    I personally find the error message a bit misleading because from a runtime perspective name could of course be something else (up until the isinstance check), i.e. it is technically not "always an instance of str". But from a static type checker's perspective that complaint makes sense.

    Python is a dynamically typed language and that philosophy carries over to type annotations. There is a reason they are also referred to as "type hints". It is extremely un-pythonic to strictly check the argument types inside a function.

    That is what the annotations are for. They tell the user of the function: "These are the types I expect in the body of this function. You can pass something else, but it might cause errors, unexpected behavior or break everything. Do it at your own peril."

    I assume there is more going on in your actual function because right now it seems semantically redundant. But my suggestion is to get rid of the isinstance check. Did you decide to annotate the name parameter with the type str? Good. Then proceed in the function body under the assumption that that is what the argument will be. It is not your job, to check the type. It is the caller's job to call your function properly (or handle the consequences).