Python Glossary Русский

Python 3.5+typingterm

typing.NewType

generics and parameters

A factory of distinct alias types: it creates a 'separate' type over a base one for type checking; at run time the call returns its argument unchanged.

Syntax

UserId = typing.NewType('UserId', int)

NewType exists purely for the type checker: at runtime UserId is not a class, isinstance against it raises, you can't subclass it, and it validates nothing. Its whole point is keeping UserId distinct from a bare int — a plain alias UserId = int is interchangeable with int, whereas NewType makes mixing the two an error.

Examples

from typing import NewType
UserId = NewType('UserId', int)
print(UserId(5))   # → 5
print(type(UserId(5)))   # → <class 'int'>
print(UserId.__name__, UserId.__supertype__)   # → UserId <class 'int'>
print(UserId(5) + 1)   # → 6
print(isinstance(5, UserId))   # → TypeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy