Hacktoberfest 2026: die Issues, die Maintainer für den Oktober markiert haben – offen und einsteigerfreundlich. Hacktoberfest-Issues durchsuchen

Add safer types of casts

Offen
#565 6 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Bewertung

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

Rechercherichtung

Beginne mit der Überprüfung der im Issue-Text vorgeschlagenen Downcast- und Upcast-Semantik. Es werden keine Dateien, Tests oder Einstiegspunkte genannt; der erste Schritt besteht darin, ein abgestimmtes Design festzulegen, wonach Implementierung und Tests erforderlich wären.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

topic: feature

The only form of cast expression we have is intended to completely bypass the type system. This is like most forms of casting in C (not counting conversions) -- it never fails either at runtime or at compile time.

Maybe we can add two new types of casts:

Downcast

downcast(T, E) checks at compile time that the type of expression E is a supertype of T, and checks at runtime that E is in fact an instance of T. As a special case, if the type of E is Any, the compile time check always succeeds, but the runtime check is still performed.

A possible implementation:

def downcast(type, expr):
    assert isinstance(expr, type)
    return expr

It's intentional that this uses assert (though debatable): the intended use case is currently handled by inserting the same assert manually. IOW:

x = downcast(type, expr)

is roughly equivalent to:

assert isinstance(expr, type)
x = expr
Upcast

Probably much less needed, but proposed for symmetry and because occasionally it's useful. upcast(T, E) should check at compile time that T is a supertype of the type of E, and at runtime it's a no-op.

A possible implementation:

def upcast(type, expr):
    return expr

This fragment:

x = upcast(type, expr)

is roughly equivalent to:

x: type = expr

except that it works even if the type of x has already been declared.

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

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus python/typing

Alle Issues in python/typing

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

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