Type system extensions for programs checked with the mypy type checker.
npx @tessl/cli install tessl/pypi-mypy-extensions@1.1.0Type system extensions for programs checked with the mypy type checker. This package provides experimental extensions to Python's standard typing module that are specifically supported by the mypy type checker and mypyc compiler.
pip install mypy-extensionsimport mypy_extensionsImport specific components:
from mypy_extensions import TypedDict, i64, i32, i16, u8
from mypy_extensions import Arg, DefaultArg, NamedArg, DefaultNamedArg, VarArg, KwArg
from mypy_extensions import trait, mypyc_attr, FlexibleAliasFor typing support in function signatures:
from typing import Any # Used in mypy_extensions function signaturesfrom mypy_extensions import TypedDict, i64, i32, trait
# TypedDict usage (deprecated - use typing.TypedDict instead)
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
Point2D = TypedDict('Point2D', {'x': int, 'y': int})
point = Point2D(x=1, y=2)
print(point) # {'x': 1, 'y': 2}
# Native integer types for mypyc
big_number = i64(2**63 - 1) # Behaves like int() at runtime
small_number = i32(42)
# Trait decorator
@trait
class Drawable:
def draw(self) -> None: ...Creates dictionary types with specific key-value type annotations for static type checking. Note: This is deprecated - use typing.TypedDict or typing_extensions.TypedDict instead.
def TypedDict(typename, fields=None, *, total=True, **kwargs):
"""
Create a typed dictionary class.
Args:
typename (str): Name of the TypedDict class
fields (dict, optional): Dictionary mapping field names to types
total (bool): Whether all fields are required (default: True)
**kwargs: Alternative way to specify fields as keyword arguments
Returns:
type: A new TypedDict class that behaves like dict at runtime
Raises:
TypeError: If both fields dict and kwargs are provided
DeprecationWarning: Always emitted to encourage migration to typing.TypedDict
"""Usage patterns:
# Functional syntax with dict
Point2D = TypedDict('Point2D', {'x': int, 'y': int})
# Functional syntax with kwargs
Point2D = TypedDict('Point2D', x=int, y=int)
# Class syntax (Python 3.6+)
class Point2D(TypedDict):
x: int
y: int
# Partial/optional fields
Options = TypedDict('Options', {'debug': bool, 'verbose': bool}, total=False)Type constructors for creating detailed Callable type annotations. These are runtime noops that return their type argument unchanged.
def Arg(type=Any, name=None):
"""
A normal positional argument.
Args:
type: The argument's type (default: Any)
name: Optional argument name for documentation
Returns:
The type argument unchanged
"""
def DefaultArg(type=Any, name=None):
"""
A positional argument with a default value.
Args:
type: The argument's type (default: Any)
name: Optional argument name for documentation
Returns:
The type argument unchanged
"""
def NamedArg(type=Any, name=None):
"""
A keyword-only argument.
Args:
type: The argument's type (default: Any)
name: Optional argument name for documentation
Returns:
The type argument unchanged
"""
def DefaultNamedArg(type=Any, name=None):
"""
A keyword-only argument with a default value.
Args:
type: The argument's type (default: Any)
name: Optional argument name for documentation
Returns:
The type argument unchanged
"""
def VarArg(type=Any):
"""
A *args-style variadic positional argument.
Args:
type: The type of the variadic arguments (default: Any)
Returns:
The type argument unchanged
"""
def KwArg(type=Any):
"""
A **kwargs-style variadic keyword argument.
Args:
type: The type of the variadic keyword arguments (default: Any)
Returns:
The type argument unchanged
"""Fixed-width integer types that provide mypyc-specific optimizations while maintaining int compatibility at runtime.
class i64:
"""
64-bit signed integer type for mypyc compilation.
Behaves like int() at runtime:
- Constructor converts numbers/strings to int
- isinstance(x, i64) equivalent to isinstance(x, int)
"""
def __new__(cls, x=0, base=None):
"""
Create a 64-bit integer.
Args:
x: Number or string to convert (default: 0)
base: Number base for string conversion (optional)
Returns:
int: The converted integer value
"""
class i32:
"""
32-bit signed integer type for mypyc compilation.
Behaves like int() at runtime:
- Constructor converts numbers/strings to int
- isinstance(x, i32) equivalent to isinstance(x, int)
"""
def __new__(cls, x=0, base=None):
"""
Create a 32-bit integer.
Args:
x: Number or string to convert (default: 0)
base: Number base for string conversion (optional)
Returns:
int: The converted integer value
"""
class i16:
"""
16-bit signed integer type for mypyc compilation.
Behaves like int() at runtime:
- Constructor converts numbers/strings to int
- isinstance(x, i16) equivalent to isinstance(x, int)
"""
def __new__(cls, x=0, base=None):
"""
Create a 16-bit integer.
Args:
x: Number or string to convert (default: 0)
base: Number base for string conversion (optional)
Returns:
int: The converted integer value
"""
class u8:
"""
8-bit unsigned integer type for mypyc compilation.
Behaves like int() at runtime:
- Constructor converts numbers/strings to int
- isinstance(x, u8) equivalent to isinstance(x, int)
"""
def __new__(cls, x=0, base=None):
"""
Create an 8-bit unsigned integer.
Args:
x: Number or string to convert (default: 0)
base: Number base for string conversion (optional)
Returns:
int: The converted integer value
"""Usage example:
# These behave like int() at runtime but provide type hints for mypyc
count = i32(42)
big_id = i64(2**50)
small_flag = u8(255)
hex_value = i16("ff", 16) # Convert hex string
# Type checking with isinstance
assert isinstance(count, i32) # True (equivalent to isinstance(count, int))
assert isinstance(count, int) # Also Truedef trait(cls):
"""
Mark a class as a trait (protocol-like interface).
Args:
cls: The class to mark as a trait
Returns:
The class unchanged (identity function at runtime)
"""Usage:
@trait
class Drawable:
def draw(self) -> None: ...
@trait
class Serializable:
def serialize(self) -> bytes: ...def mypyc_attr(*attrs, **kwattrs):
"""
Decorator for specifying mypyc-specific attributes on classes/functions.
Args:
*attrs: Positional mypyc attribute specifications
**kwattrs: Keyword mypyc attribute specifications
Returns:
Identity decorator function (noop at runtime)
"""Usage:
@mypyc_attr(allow_interpreted_subclasses=True)
class FastClass:
passAdvanced type alias construct supporting flexible parameterization.
FlexibleAlias: _FlexibleAliasCls
"""
Advanced type alias that supports flexible parameterization.
Used with subscript syntax for complex type aliasing scenarios.
"""Usage:
# Used in complex type aliasing scenarios
MyAlias = FlexibleAlias[int, str, bool]# Accessible via module attribute access - triggers DeprecationWarning
NoReturn: type
"""
Type indicating a function never returns (deprecated).
Use typing.NoReturn or typing_extensions.NoReturn instead.
Raises:
DeprecationWarning: Always emitted when accessed
"""Usage (deprecated):
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
from mypy_extensions import NoReturn
def never_returns() -> NoReturn:
raise RuntimeError("This never returns")# TypeError when using isinstance/issubclass
Point2D = TypedDict('Point2D', {'x': int, 'y': int})
isinstance({}, Point2D) # Raises TypeError
issubclass(dict, Point2D) # Raises TypeError
# TypeError for invalid field types
TypedDict('Bad', {'field': ()}) # Raises TypeError
# TypeError for mixing dict and kwargs
TypedDict('Bad', {'x': int}, y=int) # Raises TypeError# TypedDict usage emits DeprecationWarning
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
Point2D = TypedDict('Point2D', {'x': int, 'y': int})
# NoReturn access emits DeprecationWarning
from mypy_extensions import NoReturn # Warns to use typing.NoReturntyping.TypedDict (Python 3.8+) or typing_extensions.TypedDicttyping.NoReturn (Python 3.6.2+) or typing_extensions.NoReturn