python / python/mypy

Add typed attribute to third party class.

Offen
#9,823 1 Kommentar 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

feature
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Feature

I would like to be able to add a (typed) attribute to a third-party class instance.

To give a specific example, Flask's current_app, and Flask-AppBuilder. Some example code:

    def my_view(self):
        reveal_type(current_app.appbuilder)
        if current_app.appbuilder.sm.has_access(...):
            ...

The reveal_type here shows Any: airflow/www/views.py:850: note: Revealed type is 'Any'

Things I tried:

  1. To add a typed attribute myself:

    if TYPE_CHECKING:
        current_app.appbuilder = AppBuilder(None)
        reveal_type(current_app.appbuilder)
    

    Didn't work: airflow/www/views.py:115: note: Revealed type is 'Any'

  2. A partial type stub file

    I could use stubgen etc to create a stub file for all of flask and then edit the type in flask.globals, but this presents a maintenance burden that I don't want (keeping it in sync).

    I searched for any way I could to have a "partial" stub file -- if I could have a stubs/flask/globals.pyi with out neededing all the rest of the type stubs for this module, but couldn't get it working - likely not supported.

Pitch

I don't know what the feature would look like, but for the flask ecosystem it is fairly common to add properties on to the global flask object, or the g global variable, and I would love to be able to type-check my use of them, without needing to cast it at each use.

This issue is mostly a request for help/ "is there any sensible way of doing this?"

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, die reveal_type-Ergebnisse in airflow/www/views.py:850 und den TYPE_CHECKING-Versuch um Zeile 115 herum zu reproduzieren. Prüfe, wie Flask's flask.globals-Typen und stubgen Attribute von Drittanbietern behandeln. Als erledigt gilt, wenn das Issue einen dokumentierten, wartbaren Ansatz oder ein klar abgegrenztes Type-Checker-Feature zum Typisieren solcher Attribute ohne einen vollständigen Ersatz-Stub enthält.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
flask, python
Bereich
tooling
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Muss geklärt werden
Anfängerfreundlichkeit
25/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.