Skip to content

S101 should ignore assert statements in if TYPE_CHECKING blocks #3958

@bryanforbes

Description

@bryanforbes

Ruff version: 0.0.261

When writing type-checked code, it is sometimes necessary to let the type checker know about conditions it cannot be aware of using if TYPE_CHECKING blocks. Here's a (contrived) example:

from __future__ import annotations

from typing import TYPE_CHECKING


class Thing:
    some_prop: str | None

    def _init(self) -> None:
        self.some_prop = 'set'

    def _internal_method(self, arg: str) -> None:
        print(arg)

    def start(self) -> None:
        self._init()

        if TYPE_CHECKING:
            assert self.some_prop is not None

        self._internal_method(self.some_prop)

There is no way for the type checker to know that _init() set some_prop, so it still thinks some_prop is str | None, so we have to help it out with an assert statement. Obviously, if TYPE_CHECKING blocks don't run at runtime, so the assert will never run. It would be nice if ruff ignored assert statements in if TYPE_CHECKING blocks for the S101 rule.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions