python / python/mypy

Staticmethod's generated by closures are not recognized as being static

Open
#17,438 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

When using a closure to generate static methods, the resulting static method is not properly identified by mypy as being a static method. This causes mypy to complain about using the static method decorator for the inner function, and also about resulting calls to the function when using self.my_static_method

This code reproduces the issue:

from typing import Callable

class Foo:

    @staticmethod
    def add_to(num: int) -> Callable[[int], int]:
        @staticmethod
        def add_to_inner(x: int) -> int:
            return x + num
        return add_to_inner

    add1 = add_to(1)

    def __init__(self, value: int):
        self.value = value
        self.value_plus_1 = self.add1(value)


if __name__ == "__main__":
    f = Foo(10)
    print(f.value)
    print(f.value_plus_1)

When evaluated with mypy I get the errors:

$ mypy mypy-nested-static.py
mypy-nested-static.py:7: error: "staticmethod" used with a non-method  [misc]
mypy-nested-static.py:16: error: Invalid self argument "Foo" to attribute function "add1" with type "Callable[[int], int]"  [misc]
mypy-nested-static.py:16: error: Too many arguments  [call-arg]

This pattern is admittedly a bit strange but I believe it should be valid. I bumped into this when using a library that abuses static methods a little bit so my hands were a bit tied to this design.

Version info: mypy 1.10.0 (compiled: yes)

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

Start by running the provided nested-static reproducer with mypy 1.10.0 and confirm the three reported errors. Trace the staticmethod and callable attribute checks involved; done means the reproducer no longer reports those errors while preserving valid staticmethod behavior.

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.