pythonvisual-studio-codepylance

Suppress Pylance type annotation warning in VS Code


At the company I'm working we use type annotation to define the expected return type from a function. Most developers are using PyCharm but I prefer to stick with VS Code.

The following line in the VS Code IDE:

def example() -> [str]:

Raises a Pylance warning:

List expression not allowed in type annotation
  Use List[T] to indicate a list type or Union[T1, T2] to indicate a union typePylance

And would like me to use:

def example() -> List[str]

Although fixing this would require me to go over the whole code base and won't be accepted for a pull request. As I can live with this warning, I would like to suppress it.


Solution

  • Pylance supports PEP 484

    A number of existing or potential use cases for function annotations exist, which are incompatible with type hinting. These may confuse a static type checker. However, since type hinting annotations have no runtime behavior (other than evaluation of the annotation expression and storing annotations in the _annotations_ attribute of the function object), this does not make the program incorrect -- it just may cause a type checker to emit spurious warnings or errors.

    To mark portions of the program that should not be covered by type hinting, you can use one or more of the following:

    a # type: ignore comment;
    a @no_type_check decorator on a class or function;
    a custom class or function decorator marked with @no_type_check_decorator.

    Alternatively you can create a pyrightconfig.json for Pyright (as that's what Pylance is using underneath) or a pyproject.toml in project's root directory, and specify which types of errors to ignore. You can see the error type in the hover widget where error messages appear.

    pyrightconfig.json example:

    {
            "reportGeneralTypeIssues": false,
    }
    

    pyproject.toml example:

    [tool.pyright]
    reportGeneralTypeIssues = false
    

    See Type Check Diagnostics Settings for more.