CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-beartype

Unbearably fast near-real-time hybrid runtime-static type-checking in pure Python

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

typing-compatibility.mddocs/

Typing Compatibility

Enhanced typing module compatibility layer with optimizations and forward compatibility features. The beartype.typing module provides all standard typing attributes with performance improvements and preservation of deprecated features for future Python versions.

Capabilities

Forward Compatibility

Preserve PEP 585-deprecated typing attributes to maintain compatibility with future Python versions.

# PEP 585 deprecated attributes preserved for forward compatibility
from beartype.typing import (
    Dict, List, Set, FrozenSet, Tuple, Type,
    Callable, Collection, Container, Mapping, Sequence,
    Iterable, Iterator, Generator, Coroutine,
    AsyncIterable, AsyncIterator, AsyncGenerator,
    Match, Pattern, AbstractSet, ChainMap, Counter,
    DefaultDict, Deque, OrderedDict
)

Usage examples:

from beartype.typing import List, Dict, Optional
from beartype import beartype

# Works across all Python versions
@beartype
def process_data(items: List[str]) -> Dict[str, int]:
    return {item: len(item) for item in items}

@beartype
def merge_configs(
    primary: Dict[str, str], 
    secondary: Optional[Dict[str, str]] = None
) -> Dict[str, str]:
    if secondary:
        return {**primary, **secondary}
    return primary

Standard Typing Attributes

All standard typing module attributes are available through beartype.typing.

# Core typing attributes
from beartype.typing import (
    Any, Union, Optional, Final, ClassVar,
    TypeVar, Generic, Protocol, Literal,
    Annotated, ForwardRef, NewType,
    get_type_hints, get_origin, get_args,
    cast, overload, no_type_check
)

Version-Aware Imports

Conditional imports based on Python version with automatic fallbacks.

# Python 3.10+ features
from beartype.typing import (
    TypeAlias, TypeGuard, ParamSpec, Concatenate,
    ParamSpecArgs, ParamSpecKwargs, is_typeddict
)

# Python 3.11+ features  
from beartype.typing import (
    Self, LiteralString, Never, NotRequired, Required,
    TypeVarTuple, Unpack, assert_never, assert_type,
    reveal_type, dataclass_transform
)

# Python 3.12+ features
from beartype.typing import (
    TypeAliasType, override
)

# Python 3.13+ features
from beartype.typing import (
    TypeIs, ReadOnly, NoDefault,
    get_protocol_members, is_protocol
)

Optimized Protocol Support

Enhanced Protocol implementation with better runtime performance.

from beartype.typing import Protocol, runtime_checkable

@runtime_checkable  
class Drawable(Protocol):
    def draw(self) -> str: ...

# Optimized protocol checking
class Circle:
    def draw(self) -> str:
        return "Drawing circle"

# More efficient isinstance checks
assert isinstance(Circle(), Drawable)

Usage examples:

from beartype.typing import Protocol, runtime_checkable
from beartype import beartype

@runtime_checkable
class Serializable(Protocol):
    def serialize(self) -> dict: ...
    def deserialize(self, data: dict) -> None: ...

@beartype
def save_object(obj: Serializable) -> dict:
    return obj.serialize()

class User:
    def __init__(self, name: str):
        self.name = name
    
    def serialize(self) -> dict:
        return {"name": self.name}
    
    def deserialize(self, data: dict) -> None:
        self.name = data["name"]

user = User("Alice")
data = save_object(user)  # Protocol automatically satisfied

Type Construction Utilities

Utilities for creating and manipulating type hints programmatically.

from beartype.typing import get_type_hints, get_origin, get_args

def inspect_function_types(func):
    """Inspect function's type hints."""
    hints = get_type_hints(func)
    for name, hint in hints.items():
        origin = get_origin(hint)
        args = get_args(hint)
        print(f"{name}: {hint} (origin: {origin}, args: {args})")

Deprecated Attribute Handling

Automatic handling of deprecated typing attributes with warnings.

# Deprecated attributes still available with warnings
from beartype.typing import ByteString, AnyStr

# These will work but may emit deprecation warnings in future versions
@beartype  
def process_bytes(data: ByteString) -> int:
    return len(data)

@beartype
def concat_strings(a: AnyStr, b: AnyStr) -> AnyStr:
    return a + b

Type Checking Integration

Integration with static type checkers while providing runtime optimizations.

from beartype.typing import TYPE_CHECKING

if TYPE_CHECKING:
    # Import expensive types only for static analysis
    from typing_extensions import TypedDict
    
    class ConfigDict(TypedDict):
        host: str
        port: int
        debug: bool
else:
    # Runtime uses regular dict
    ConfigDict = dict

Collection Type Aliases

Enhanced collection type aliases with better runtime performance.

from beartype.typing import (
    Mapping, MutableMapping, Sequence, MutableSequence,
    Set, MutableSet, ItemsView, KeysView, ValuesView,
    Collection, Container, Sized, Iterable, Iterator,
    Reversible, Hashable
)

Usage examples:

from beartype.typing import Mapping, Sequence, Set
from beartype import beartype

@beartype
def analyze_data(
    config: Mapping[str, str],
    items: Sequence[int], 
    tags: Set[str]
) -> dict:
    return {
        "config_keys": len(config),
        "item_count": len(items),
        "unique_tags": len(tags)
    }

# Works with any mapping, sequence, or set type
result = analyze_data(
    {"host": "localhost", "port": "8080"},  # dict → Mapping
    [1, 2, 3, 4, 5],                       # list → Sequence  
    {"python", "typing", "beartype"}        # set → Set
)

Advanced Type Features

Support for advanced typing features across Python versions.

from beartype.typing import (
    Callable, Awaitable, Coroutine, Generator,
    AsyncIterable, AsyncIterator, AsyncGenerator,
    ContextManager, AsyncContextManager
)

Usage examples:

from beartype.typing import Callable, Generator, AsyncIterable
from beartype import beartype
import asyncio

@beartype
def apply_function(func: Callable[[int], str], value: int) -> str:
    return func(value)

@beartype
def number_generator(start: int, end: int) -> Generator[int, None, None]:
    for i in range(start, end):
        yield i

@beartype
async def process_async_data(
    data: AsyncIterable[str]
) -> list[str]:
    results = []
    async for item in data:
        results.append(item.upper())
    return results

# Usage
result = apply_function(str, 42)  # "42"

gen = number_generator(1, 5)
numbers = list(gen)  # [1, 2, 3, 4]

Best Practices

Consistent Imports

Always import typing attributes from beartype.typing for consistency:

# Recommended
from beartype.typing import List, Dict, Optional, Union

# Instead of mixing
from typing import List, Dict
from beartype.typing import Optional, Union

Version Compatibility

Use version checks when needed for conditional features:

from beartype.typing import TYPE_CHECKING
import sys

if sys.version_info >= (3, 10):
    from beartype.typing import TypeAlias
    ConfigType: TypeAlias = dict[str, str]
else:
    ConfigType = dict

Performance Considerations

Leverage beartype.typing's optimizations for better runtime performance:

# Optimized protocol checking
from beartype.typing import Protocol, runtime_checkable

@runtime_checkable
class FastProtocol(Protocol):
    def method(self) -> int: ...

# More efficient than typing.Protocol
def check_object(obj):
    return isinstance(obj, FastProtocol)

Install with Tessl CLI

npx tessl i tessl/pypi-beartype

docs

core-type-checking.md

door-api.md

exceptions.md

import-hooks.md

index.md

typing-compatibility.md

validators.md

tile.json