CKTIS / Python
typing.NewType
Tworzy odrębny statyczny podtyp, np. dla identyfikatora opartego na int.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
UserId = NewType("UserId", int)Tworzy odrębny statyczny podtyp, np. dla identyfikatora opartego na int.
Identyfikator można podać tam, gdzie oczekiwany jest int, lecz odwrotne przypisanie nie jest automatyczne.
Podczas wykonania wywołanie zwraca ten sam obiekt bez walidacji, a suma liczb pozostaje zwykłym int.
Przykłady
from typing import NewType
UserId = NewType("UserId", int)
raw = int("1200")
value = UserId(raw)
print(value is raw, type(value + 1).__name__)
print(UserId("x"), UserId.__supertype__ is int)
Wynik
True int x True
Podczas wykonania wywołanie zwraca ten sam obiekt bez walidacji, a suma liczb pozostaje zwykłym int.