python / python/mypy

(🐞) `staticmethod` special-casing causes error to not be reported

Open
#16,161 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

If we copy the implementation of staticmethod from typeshed, mypy correctly reports the error here.

So it seems that mypys dedicated special-casing of staticmethod is causing this issue to be incorrectly not reported.

from collections.abc import Callable
from typing import Generic, ParamSpec, TypeVar, overload

P = ParamSpec("P")
T = TypeVar("T")
R_co = TypeVar("R_co", covariant=True)


def contextmanager(fn: Callable[P, R_co]) -> Callable[P, R_co]:
    def func(*args: P.args, **kwargs: P.kwargs) -> R_co:
        return fn(*args, **kwargs)
    return func


class staticmethod_copy(Generic[P, R_co]):
    @property
    def __func__(self) -> Callable[P, R_co]: ...
    @property
    def __isabstractmethod__(self) -> bool: ...
    def __init__(self, __f: Callable[P, R_co]) -> None: ...
    @overload
    def __get__(self, __instance: None, __owner: type) -> Callable[P, R_co]: ...
    @overload
    def __get__(self, __instance: T, __owner: type[T] | None = None) -> Callable[P, R_co]: ...
    __name__: str
    __qualname__: str
    @property
    def __wrapped__(self) -> Callable[P, R_co]: ...
    def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R_co: ...

# Just the relevant part of staticmethod definition that is needed
#class staticmethod(Generic[P, R_co]):
#    def __init__(self, __f: Callable[P, R_co]) -> None: ...
#    def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R_co: ...

class Foo:
    @contextmanager
    @staticmethod_copy
    def copy() -> None: ...

    @contextmanager
    @staticmethod
    def native() -> None: ...


Foo().copy()   # ✅ error: Attribute function "copy" with type "Callable[[], None]" does not accept self argument  [misc]
Foo().native()  # ❌no error

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the provided example and compare mypy's dedicated staticmethod special-casing with the copied typeshed implementation. Trace how the decorators and descriptor types are analyzed; done means mypy reports the missing-self error for Foo().native() as it does for Foo().copy().

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.