Skip to content

TCH004 false positive with submodule imports and rebinding #3821

@shiftinv

Description

@shiftinv

Importing the same top-level module through two submodule imports, one at runtime and one in a type-checking block, results in TCH004 false positives.
This is certainly more of an edge case, seems like it could be related to #60 🤔

Code:

from __future__ import annotations

from typing import TYPE_CHECKING
import importlib.util

if TYPE_CHECKING:
    import importlib.machinery


def from_spec(spec: importlib.machinery.ModuleSpec):
    return importlib.util.module_from_spec(spec)

Running ruff check --isolated --select TCH test.py (v0.0.260) produces the following error:

test.py:7:12: TCH004 Move import `importlib.machinery` out of type-checking block. Import is used for more than type hinting.

I don't know a whole lot about ruff's internals, but my assumption is that the importlib.machinery import in the type-checking block overwrites the importlib binding, and the importlib.util.module_from_spec call later resolves to that.

Metadata

Metadata

Assignees

No one assigned

    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