fpgmaas/deptry

Import in `if TYPE_CHECKING` block is detected as a violation of DEP004

Closed this issue · 1 comments

Imports in if typing.TYPE_CHECKING blocks are reported as a violation of DEP004 (library is imported but declared as a dev dependency), this makes it harder to work with some of library stubs, like types-aiobotocore-s3 as an example.

To Reproduce

  1. Install stubs:
pdm add --dev types-aiobotocore-s3
  1. Following code should trigger the error:
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from types_aiobotocore_s3 import S3Client


def func() -> S3Client:
    pass

Expected behavior

Imports in if TYPE_CHECKING blocks shouldn't be reported as a violation of existing rules, since they're (likely) not used at runtime. As an alternative maybe a different option/setting could be added to allow certain packages to be imported in if type-checking blocks 🤔

System:

  • OS: Windows 10
  • Language Version: Python 3.11.5
  • Package Manager: PDM, version 2.12.2

It would make sense to either avoid taking those imports as imported dependencies entirely, or treating them differently indeed. Unless there are use cases for doing the latter, I believe that it would be simpler to entirely ignore dependencies in if TYPE_CHECKING blocks. This feels more like an enhancement than a bug though, as this is a current limitation of the tool.

The logic that extracts imports is here. I believe that it could be updated to skip the imports that are in a if TYPE_CHECKING block.

If you want to give it a shot, let me know, I can assign the issue to you, otherwise, this might be something we work on at some point.