Unbearably fast near-real-time hybrid runtime-static type-checking in pure Python
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
DOOR (Decidedly Object-Oriented Runtime-checking) API provides advanced type hint manipulation and introspection capabilities. This object-oriented interface wraps the standard typing module with enhanced functionality for runtime type checking and validation.
Abstract base class for all type hint objects providing common interface.
class TypeHint:
"""
Abstract base class for type hint introspection objects.
Provides object-oriented interface to type hints with enhanced
runtime capabilities beyond standard typing module.
"""
def __init__(self, hint):
"""Initialize with a type hint object."""
def __eq__(self, other):
"""Test equality with another type hint."""
def __hash__(self):
"""Compute hash for use in sets and dicts."""
def __repr__(self):
"""Return string representation."""class UnionTypeHint(TypeHint):
"""
Type hint for Union types (PEP 484/604).
Represents typing.Union type hints including Optional[T] which
is equivalent to Union[T, None].
"""
@property
def args(self):
"""Tuple of union member types."""
@property
def is_optional(self):
"""True if this union includes None (i.e., Optional)."""class AnnotatedTypeHint(TypeHint):
"""
Type hint for Annotated types (PEP 593).
Represents typing.Annotated type hints with metadata.
"""
@property
def origin(self):
"""The base type being annotated."""
@property
def metadata(self):
"""Tuple of annotation metadata objects."""class CallableTypeHint(TypeHint):
"""
Type hint for Callable types.
Represents typing.Callable type hints with parameter and return types.
"""
@property
def args(self):
"""List of parameter types or Ellipsis for any parameters."""
@property
def return_type(self):
"""Return type of the callable."""class GenericTypeHint(TypeHint):
"""
Type hint for Generic types.
Represents typing.Generic base classes and their subclasses.
"""
@property
def type_vars(self):
"""Tuple of TypeVar objects used by this generic."""
class SubscriptedTypeHint(TypeHint):
"""
Type hint for subscripted generic types.
Represents generic types with concrete type arguments (e.g., List[int]).
"""
@property
def origin(self):
"""The generic base type (e.g., list for List[int])."""
@property
def args(self):
"""Tuple of type arguments (e.g., (int,) for List[int])."""class TupleFixedTypeHint(TypeHint):
"""
Type hint for fixed-length tuple types.
Represents tuple type hints with specific element types.
"""
@property
def item_types(self):
"""Tuple of element types in order."""
class TupleVariableTypeHint(TypeHint):
"""
Type hint for variable-length tuple types.
Represents tuple type hints with repeated element type.
"""
@property
def item_type(self):
"""Type of tuple elements."""class AnyTypeHint(TypeHint):
"""Type hint for typing.Any."""
class ClassTypeHint(TypeHint):
"""Type hint for class-based types."""
@property
def cls(self):
"""The class object this hint represents."""
class LiteralTypeHint(TypeHint):
"""
Type hint for Literal types (PEP 586).
Represents typing.Literal type hints with specific values.
"""
@property
def values(self):
"""Tuple of literal values."""
class NewTypeTypeHint(TypeHint):
"""
Type hint for NewType types.
Represents typing.NewType derived types.
"""
@property
def name(self):
"""Name of the new type."""
@property
def supertype(self):
"""Base type that this NewType extends."""
class TypeVarTypeHint(TypeHint):
"""
Type hint for TypeVar types.
Represents typing.TypeVar type variables.
"""
@property
def name(self):
"""Name of the type variable."""
@property
def bound(self):
"""Upper bound type or None."""
@property
def constraints(self):
"""Tuple of allowed types or empty tuple."""Runtime type checking and validation utilities.
def is_bearable(obj, hint):
"""
Test whether an object satisfies a type hint.
Parameters:
- obj: Any - Object to test
- hint: Any - Type hint to test against
Returns:
bool - True if object satisfies hint, False otherwise
"""
def die_if_unbearable(obj, hint, exc_cls=BeartypeDoorHintViolation):
"""
Raise exception if object doesn't satisfy type hint.
Parameters:
- obj: Any - Object to test
- hint: Any - Type hint to test against
- exc_cls: type - Exception class to raise on failure
Returns:
None - Returns normally if object satisfies hint
Raises:
BeartypeDoorHintViolation - If object doesn't satisfy hint
"""
def is_subhint(subhint, superhint):
"""
Test whether one type hint is a subtype of another.
Parameters:
- subhint: Any - Potential subtype hint
- superhint: Any - Potential supertype hint
Returns:
bool - True if subhint is subtype of superhint
"""Automatic type hint inference from runtime objects.
def infer_hint(obj):
"""
Infer type hint from a runtime object.
Analyzes an object and returns the most specific type hint
that describes it.
Parameters:
- obj: Any - Object to infer type hint for
Returns:
Any - Inferred type hint
"""from beartype.door import is_bearable, die_if_unbearable
from typing import List, Optional
# Test type compatibility
data = [1, 2, 3]
print(is_bearable(data, List[int])) # True
print(is_bearable(data, List[str])) # False
# Raise exception on type mismatch
value: Optional[str] = "hello"
die_if_unbearable(value, Optional[str]) # OK
try:
die_if_unbearable(42, Optional[str]) # Raises exception
except BeartypeDoorHintViolation as e:
print(f"Type violation: {e}")from beartype.door import TypeHint, UnionTypeHint, AnnotatedTypeHint
from typing import Union, Optional, Annotated
# Introspect Union types
hint = TypeHint(Optional[str])
if isinstance(hint, UnionTypeHint):
print(f"Union args: {hint.args}") # (str, NoneType)
print(f"Is optional: {hint.is_optional}") # True
# Introspect Annotated types
from beartype.vale import Is
annotated_hint = TypeHint(Annotated[int, Is[lambda x: x > 0]])
if isinstance(annotated_hint, AnnotatedTypeHint):
print(f"Base type: {annotated_hint.origin}") # int
print(f"Metadata: {annotated_hint.metadata}") # (validator,)from beartype.door import infer_hint
# Infer from simple objects
print(infer_hint(42)) # int
print(infer_hint("hello")) # str
print(infer_hint([1, 2, 3])) # List[int]
# Infer from complex structures
data = {"name": "Alice", "age": 30, "scores": [95, 87, 92]}
hint = infer_hint(data)
print(hint) # Dict[str, Union[str, int, List[int]]]from beartype.door import is_subhint
from typing import List, Sequence, Union
# Check type relationships
print(is_subhint(List[int], Sequence[int])) # True
print(is_subhint(int, Union[int, str])) # True
print(is_subhint(Union[int, str], int)) # FalseInstall with Tessl CLI
npx tessl i tessl/pypi-beartype