Suppress Pylance type annotation warning in VS Code

Question:

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.

Asked By: Joep

||

Answers:

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.

Answered By: Alexandru Dreptu

One additional option not always covered are inline ignores with specific rule names. This is great when working in a strict codebase that disallows the generic mypy style # type: ignore without a rule being specified.

Here is a common example, when type narrowing just isn’t working:

# pyright: reportUnknownMemberType=false

It’s a little more involved than your typical # type: ignore[assignment], but works well for suppressing most Pylance errors.

Further, if you’d like to look up the specific rule names manually (such as when Pylance can’t display them properly),
give this list a try: pyright/…/diagnosticRules.ts

Answered By: DataWizard