Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TCH002 false positive with singledispatch #6849

Closed
flying-sheep opened this issue Aug 24, 2023 · 1 comment · Fixed by #8934
Closed

TCH002 false positive with singledispatch #6849

flying-sheep opened this issue Aug 24, 2023 · 1 comment · Fixed by #8934
Assignees
Labels
bug Something isn't working

Comments

@flying-sheep
Copy link
Contributor

flying-sheep commented Aug 24, 2023

Playground link

functools.singledispatch’s register decorator can take a function with the first argument being type-annotated. That type annotation will then be used to dispatch.

The following code should therefore be correct with all rules active, however it claims rule violations on the annotated lines.

"""Test module."""
from __future__ import annotations

from functools import singledispatch
from typing import TYPE_CHECKING

from numpy import asarray  # TCH002: Move third-party import `numpy.typing.ArrayLike` into a type-checking block
from numpy.typing import ArrayLike  # TCH002: Move third-party import `scipy.sparse.spmatrix` into a type-checking block
from scipy.sparse import spmatrix

if TYPE_CHECKING:
    from numpy import ndarray


@singledispatch
def to_array_or_mat(a: ArrayLike | spmatrix) -> ndarray | spmatrix:
    """Convert arg to array or leaves it as sparse matrix."""
    msg = f"Unhandled type {type(a)}"
    raise NotImplementedError(msg)

@to_array_or_mat.register
def _(a: ArrayLike) -> ndarray:
    return asarray(a)

@to_array_or_mat.register
def _(a: spmatrix) -> spmatrix:
    return a
@flying-sheep
Copy link
Contributor Author

flying-sheep commented Aug 24, 2023

@ivirshup support for pydantic-like and attrs-like patterns can already be achieved via flake8-type-checking.runtime-evaluated-base-classes and flake8-type-checking.runtime-evaluated-decorators, respectively

@charliermarsh charliermarsh added the bug Something isn't working label Aug 24, 2023
@charliermarsh charliermarsh self-assigned this Nov 30, 2023
charliermarsh added a commit that referenced this issue Dec 1, 2023
## Summary

When a function uses `@functools.singledispatch`, we need to treat the
first argument of any implementations as runtime-required.

Closes #6849.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants