python / python/typing

Assertion and checking functions

Offen
#703 19 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

topic: feature
Vorherrschende Sprache
Python
Sterne
1.8k
Forks
302
Ø Merge
23 Std.
Gemergte PRs (30 T.)
8

Beschreibung

I'll just leave this here for potential future consideration as it came up on gitter's typing-dev channel. Typescript has something called assertion functions, which enables the type checker to understand that a function does not return if a certain condition is false. I think something similar, but more generalized, would be interesting, especially for unit test functions like assert_is_instance(), assert_true() etc.

def assert_positive(x: object) -> AssertsInstance["x", int]:
    assert isinstance(x, int) and x > 0

Related, checking functions could work like this:


def is_positive(x: object) -> ChecksInstance["x", int]:
    return isinstance(x, int) and x > 0

def my_func(x: Union[int, str]) -> None:
    if is_positive(x):
        # x must be an int
        ...
    else:
        # x can be an int or str
        ...

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

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 mit der verlinkten Dokumentation zu den TypeScript 3.7 assertion-functions und den Beispielen assert_positive und is_positive aus dem Issue. Da keine Repository-Dateien oder Tests genannt sind, definiere zunächst, wie generalisierte Assertion- und Prüfannotationen die Typverengung ausdrücken sollen, und dokumentiere anschließend das vereinbarte Verhalten und die erforderliche Testabdeckung.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python, typescript
Bereich
compilers
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.