python / python/mypy

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

Aperta
#17,438 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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)

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo il reproducer nested-static fornito con mypy 1.10.0 e conferma i tre errori segnalati. Traccia i controlli coinvolti di staticmethod e degli attributi callable; il lavoro è completato quando il reproducer non segnala più questi errori, mantenendo il comportamento valido di staticmethod.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.