Skip to content

SIM108 suggests to convert TYPE_CHECKING block #8071

@mrcljx

Description

@mrcljx

When using type checkers like Mypy, it's sometimes necessary to give them different code to inspect. This is done via if TYPE_CHECKING blocks, e.g.

from typing import TYPE_CHECKING
import functools

def _retry(callback, count: int) -> None:
  pass

if TYPE_CHECKING:
  retry = _retry
else:
  retry = functools.partial(_retry, count=3)

The rule SIM108 will emit (or --unsafe-fixes):

example.py:7:1: SIM108 Use ternary operator `retry = _retry if TYPE_CHECKING else functools.partial(_retry, count=3)` instead of `if`-`else`-block

In that case, type checkers like Mypy would not enable their special handling of if TYPE_CHECKING though, inferring the type of retry as a union type between the two expressions.

The SIM108 rule should ignore this case.

  • ruff --isolated --select SIM108 example.py
  • Version: 0.1.0

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions