Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
typing.NewType is a utility used to create distinct, strongly-typed aliases for existing types that are enforced exclusively by static type checkers. At runtime, a NewType is completely transparent, introduces zero overhead, and resolves directly to its original base type.
Syntax
Static Type Checker Behavior
To static type analyzers (likemypy or pyright), NewType creates a unidirectional inheritance relationship. The analyzer treats the NewType as a subclass of the base type, enforcing standard subtyping rules (the Liskov Substitution Principle).
- Subtyping: A
NewTypecan be passed to any function expecting the base type, just as a subclass can be used in place of its base class. - Strictness: The base type cannot be passed to a function expecting the
NewType. - Operation resolution: Performing standard operations (like arithmetic) on a
NewTypeyields the base type, not theNewType.
Runtime Behavior
At runtime,NewType does not create a new class or allocate new memory structures.
- Pre-Python 3.10:
NewTypereturned a standard nested function:def new_type(x): return x. - Python 3.10+:
NewTypereturns an instance of thetyping.NewTypeclass, which implements a__call__method that acts as an identity function, returning the exact object passed to it.
NewType vs. TypeAlias
It is critical to distinguish NewType from standard type aliases.
Master Python with Deep Grasping Methodology!Learn More





