Skip to content

[flake8-type-checking] False positives/negatives for TC001-004 for overlapping module imports #15723

@Daverball

Description

@Daverball

Description

This bug was discovered in #15719

Given something like:

from __future__ import annotations

import importlib.abc
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import importlib.machinery

class Foo(importlib.abc.MetaPathFinder):
    def bar(self) -> importlib.machinery.ModuleSpec: ...

importlib.machinery will incorrectly be flagged with TC004, since importlib.abc.MetaPathFinder binds to the same binding as importlib.machinery.ModuleSpec, so since the former is used at runtime, it thinks that importlib.machinery needs to be moved outside the TYPE_CHECKING block.

Combining the two imports into a shared binding makes sense, since what will be looked up is importlib and not importlib.machinery or importlib.abc.

This means that when we're checking the import bindings we need to expand the single importlib binding to its two import statements importlib.abc and importlib.machinery and for each reference check which of the two imports will actually be relevant.

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