Skip to content

API Reference

Reuse generic class type arguments at runtime.

This library provides a decorator that allows you to mark a class as a 'runtime generic': after instantiation, the class will have a __args__ attribute that contains the type arguments of the instance.

Examples:

from __future__ import annotations

import io
from typing import TYPE_CHECKING, Generic, TypeVar

from runtime_generics import get_alias, get_type_arguments, runtime_generic, type_check

if TYPE_CHECKING:
    from typing import IO, Literal, overload

T = TypeVar("T", str, bytes)


@runtime_generic
class IOWrapper(Generic[T]):
    data_type: type[T]

    def __init__(self, stream: IO[T]) -> None:
        (self.data_type,) = get_type_arguments(self)
        self.stream = stream

    if TYPE_CHECKING:
        @overload
        def is_binary(self: IOWrapper[bytes]) -> Literal[True]: ...

        @overload
        def is_binary(self: IOWrapper[str]) -> Literal[False]: ...

    def is_binary(self) -> bool:
        # alternatively here: `self.data_type == bytes`
        return type_check(self, IOWrapper[bytes])

    def __repr__(self) -> str:
        return f"<{get_alias(self)} object at ...>"


my_binary_data = IOWrapper[bytes](io.BytesIO(b"foo"))
assert my_binary_data.data_type is bytes
assert my_binary_data.is_binary()
assert repr(IOWrapper[str](io.StringIO())) == "<__main__.IOWrapper[str] object at ...>"

Classes:

  • GenericArgs

    Marker class for type arguments of runtime generics.

Functions:

  • get_parametrization

    Map type parameters to type arguments in a generic alias.

  • get_parents

    Get all parametrized parents of a runtime generic class or instance.

  • get_mro

    Get all parametrized parents of a runtime generic using the C3 algorithm.

  • get_alias

    For any runtime generic (class, instance), find the most relevant generic alias.

  • runtime_generic_patch

    Patch objects to support runtime generics.

  • no_alias

    Mark a classmethod as not being passed a generic alias in place of cls.

  • get_type_arguments

    Get all type arguments of a runtime generic.

  • runtime_generic_proxy

    Create a runtime generic descriptor with a result type.

  • runtime_generic_init

    Initialize a runtime generic instance.

  • runtime_generic

    Mark a class as a runtime generic.

  • type_check

    Examine whether a runtime generic is a valid subtype of another runtime generic.

GenericArgs

Bases: tuple

Marker class for type arguments of runtime generics.

get_parametrization(runtime_generic)

Map type parameters to type arguments in a generic alias.

Source code in runtime_generics/__init__.py
345
346
347
348
349
350
def get_parametrization(runtime_generic: Any) -> dict[Any, Any]:
    """Map type parameters to type arguments in a generic alias."""
    return _get_parametrization(
        _get_generic_signature(runtime_generic).__args__,
        get_type_arguments(runtime_generic),
    )

get_parents(cls)

Get all parametrized parents of a runtime generic class or instance.

Source code in runtime_generics/__init__.py
379
380
381
def get_parents(cls: Any) -> tuple[Any, ...]:
    """Get all parametrized parents of a runtime generic class or instance."""
    return tuple(_get_parents(cls))

get_mro(cls)

Get all parametrized parents of a runtime generic using the C3 algorithm.

Source code in runtime_generics/__init__.py
420
421
422
def get_mro(cls: Any) -> tuple[Any, ...]:
    """Get all parametrized parents of a runtime generic using the C3 algorithm."""
    return tuple(_get_mro(cls))

get_alias(rg)

For any runtime generic (class, instance), find the most relevant generic alias.

Parameters:

  • rg

    (Any) –

    Any form of a runtime generic.

Examples:

>>> from typing import Generic, TypeVar
>>> T = TypeVar("T")
...
>>> @runtime_generic
... class Foo(Generic[T]):
...     pass
...
>>> get_alias(Foo)
runtime_generics.Foo[typing.Any]
>>> get_alias(Foo())
runtime_generics.Foo[typing.Any]
>>> get_alias(Foo[int])
runtime_generics.Foo[int]
>>> get_alias(Foo[int]())
runtime_generics.Foo[int]
Source code in runtime_generics/__init__.py
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
def get_alias(rg: Any) -> Any:
    """
    For any runtime generic (class, instance), find the most relevant generic alias.

    Parameters
    ----------
    rg
        Any form of a runtime generic.

    Examples
    --------
    ```py
    >>> from typing import Generic, TypeVar
    >>> T = TypeVar("T")
    ...
    >>> @runtime_generic
    ... class Foo(Generic[T]):
    ...     pass
    ...
    >>> get_alias(Foo)
    runtime_generics.Foo[typing.Any]
    >>> get_alias(Foo())
    runtime_generics.Foo[typing.Any]
    >>> get_alias(Foo[int])
    runtime_generics.Foo[int]
    >>> get_alias(Foo[int]())
    runtime_generics.Foo[int]

    ```

    """
    try:
        args = rg.__args__
    except AttributeError:
        return _get_default_alias(rg)
    else:
        if any(
            _has_origin(arg) and arg.__origin__ is Unpack or isinstance(arg, TypeVar)
            for arg in args
        ):
            return _get_default_alias(rg)
    if rg.__module__ == "typing" and rg._name:  # noqa: SLF001
        return _AliasProxy(getattr(typing, rg._name), rg.__args__)  # noqa: SLF001
    return _AliasProxy(rg.__origin__, rg.__args__)

runtime_generic_patch(*objects, stack_offset=2)

Patch objects to support runtime generics.

Source code in runtime_generics/__init__.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
@contextmanager
def runtime_generic_patch(*objects: object, stack_offset: int = 2) -> Iterator[None]:
    """Patch `objects` to support runtime generics."""
    variables = {}

    with suppress(ValueError, TypeError, RuntimeError):
        variables = map_args_to_identifiers(
            *objects,
            stack_offset=stack_offset + 1,
            function=runtime_generic_patch,
        )

    if objects and not variables:
        msg = (
            "Failed to resolve objects to patch.\n"
            "This might have occured on incorrect call to `runtime_generic_patch()`.\n"
            "Call `runtime_generic_patch()` only with explicit identifiers, "
            "like `runtime_generic_patch(List, Tuple)`."
        )
        raise ValueError(msg)

    backframe_globals = inspect.stack()[stack_offset].frame.f_globals
    previous_state = backframe_globals.copy()

    # fmt: off
    backframe_globals.update({
        identifier: runtime_generic_proxy(obj)
        for identifier, obj in variables.items()
    })
    # fmt: on

    try:
        yield
    finally:
        backframe_globals.update(previous_state)

no_alias(cls_method)

Mark a classmethod as not being passed a generic alias in place of cls.

Source code in runtime_generics/__init__.py
548
549
550
551
def no_alias(cls_method: Callable[_P, _R]) -> Callable[_P, _R]:
    """Mark a classmethod as not being passed a generic alias in place of cls."""
    cls_method.__no_alias__ = True  # type: ignore[attr-defined]
    return cls_method

get_type_arguments(rg)

Get all type arguments of a runtime generic.

Parameters:

  • rg

    (object) –

    An class that was decorated with @runtime_generic or its instance.

Returns:

  • args

    The type arguments of the examined runtime generic.

Examples:

>>> from typing import Generic, TypeVar
>>> T = TypeVar("T")
...
>>> @runtime_generic
... class Foo(Generic[T]):
...     pass
>>> args: tuple[type[int]] = get_type_arguments(Foo[int]())
>>> args
(<class 'int'>,)
Source code in runtime_generics/__init__.py
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
def get_type_arguments(rg: object) -> tuple[type[Any], ...]:
    """
    Get all type arguments of a runtime generic.

    Parameters
    ----------
    rg
        An class that was decorated with `@runtime_generic` or its instance.

    Returns
    -------
    args
        The type arguments of the examined runtime generic.

    Examples
    --------
    ```python
    >>> from typing import Generic, TypeVar
    >>> T = TypeVar("T")
    ...
    >>> @runtime_generic
    ... class Foo(Generic[T]):
    ...     pass
    >>> args: tuple[type[int]] = get_type_arguments(Foo[int]())
    >>> args
    (<class 'int'>,)

    ```

    """
    args = getattr(rg, "__args__", ())
    return tuple(args) if isinstance(args, GenericArgs) else _typing_get_args(args)

runtime_generic_proxy(result_type)

Create a runtime generic descriptor with a result type.

Source code in runtime_generics/__init__.py
588
589
590
591
592
593
594
595
596
def runtime_generic_proxy(result_type: Any) -> Any:
    """Create a runtime generic descriptor with a result type."""
    parameters = _get_generic_signature(result_type).__args__

    @partial(runtime_generic, result_type=result_type)
    class _Proxy(Generic[parameters]):  # type: ignore[misc]
        pass

    return cast(Any, _Proxy)

runtime_generic_init(self, args, origin)

Initialize a runtime generic instance.

Source code in runtime_generics/__init__.py
599
600
601
602
603
604
605
606
def runtime_generic_init(
    self: object,
    args: tuple[object, ...],
    origin: object,
) -> None:
    """Initialize a runtime generic instance."""
    vars(self).setdefault("__args__", args)
    vars(self).setdefault("__origin__", origin)

runtime_generic(cls, result_type=None)

Mark a class as a runtime generic.

This is a class decorator that dynamically adds a __class_getitem__ descriptor to the class. This method returns a callable that takes type arguments and returns a new instance of the class with the __args__ attribute set to the type arguments.

Examples:

>>> from typing import Generic, TypeVar
>>> T = TypeVar("T")
...
>>> @runtime_generic
... class Foo(Generic[T]):
...     pass
...
>>> Foo[int]().__args__
(<class 'int'>,)
Source code in runtime_generics/__init__.py
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
def runtime_generic(
    cls: _R,
    result_type: Any = None,
) -> _R:
    """
    Mark a class as a runtime generic.

    This is a class decorator that dynamically adds a `__class_getitem__` descriptor
    to the class. This method returns a callable that takes type arguments and returns
    a new instance of the class with the `__args__` attribute set to the type arguments.

    Examples
    --------
    ```python
    >>> from typing import Generic, TypeVar
    >>> T = TypeVar("T")
    ...
    >>> @runtime_generic
    ... class Foo(Generic[T]):
    ...     pass
    ...
    >>> Foo[int]().__args__
    (<class 'int'>,)

    ```

    """
    _setup_runtime_generic(cls, result_type=result_type)
    return cls

type_check(subtype, cls)

Examine whether a runtime generic is a valid subtype of another runtime generic.

Variance is supported. TypeVar bounds are not yet supported.

Parameters:

  • subtype

    (Any) –

    The runtime generic to examine.

  • cls

    (Any) –

    The supertype runtime generic.

Examples:

>>> from typing import Any, Dict, Generic, TypeVar
...
>>> T = TypeVar("T")
>>> T_co = TypeVar("T_co", covariant=True)
>>> T_contra = TypeVar("T_contra", contravariant=True)
...
>>> type_check(Dict[str, int], Dict[str, bool])  # KT, VT - invariant
False
>>> @runtime_generic
... class Foo(Generic[T, T_co, T_contra]):
...     pass
...
>>> @runtime_generic
... class Bar(Generic[T_contra, T_co, T], Foo[T, T_co, T_contra]):
...     pass
...
>>> type_check(Foo[int, int, int], Foo[int, int, int])
True
>>> type_check(Foo[int, bool, int], Foo[int, int, int])
True
>>> type_check(Foo[int, int, int], Foo[int, int, bool])
True
>>> type_check(Foo[int, int, int], Foo[int, bool, int])
False
>>> type_check(Foo[int, int, bool], Foo[int, int, int])
False
>>> type_check(Bar[int, int, int], Foo[int, int, bool])
True
>>> type_check(Bar[bool, int, int], Foo[int, int, int])
False
>>> type_check(Bar[int, bool, int], Foo[int, int, int])
True

Returns:

  • bool

    Whether subtype is a valid subtype of cls.

Source code in runtime_generics/__init__.py
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
def type_check(subtype: Any, cls: Any) -> bool:
    """
    Examine whether a runtime generic is a valid subtype of another runtime generic.

    Variance is supported. TypeVar bounds are not yet supported.

    Parameters
    ----------
    subtype
        The runtime generic to examine.
    cls
        The supertype runtime generic.

    Examples
    --------
    ```python
    >>> from typing import Any, Dict, Generic, TypeVar
    ...
    >>> T = TypeVar("T")
    >>> T_co = TypeVar("T_co", covariant=True)
    >>> T_contra = TypeVar("T_contra", contravariant=True)
    ...
    >>> type_check(Dict[str, int], Dict[str, bool])  # KT, VT - invariant
    False
    >>> @runtime_generic
    ... class Foo(Generic[T, T_co, T_contra]):
    ...     pass
    ...
    >>> @runtime_generic
    ... class Bar(Generic[T_contra, T_co, T], Foo[T, T_co, T_contra]):
    ...     pass
    ...
    >>> type_check(Foo[int, int, int], Foo[int, int, int])
    True
    >>> type_check(Foo[int, bool, int], Foo[int, int, int])
    True
    >>> type_check(Foo[int, int, int], Foo[int, int, bool])
    True
    >>> type_check(Foo[int, int, int], Foo[int, bool, int])
    False
    >>> type_check(Foo[int, int, bool], Foo[int, int, int])
    False
    >>> type_check(Bar[int, int, int], Foo[int, int, bool])
    True
    >>> type_check(Bar[bool, int, int], Foo[int, int, int])
    False
    >>> type_check(Bar[int, bool, int], Foo[int, int, int])
    True

    ```

    Returns
    -------
    bool
        Whether `subtype` is a valid subtype of `cls`.

    """
    subtype = get_alias(subtype)
    cls = get_alias(cls)

    for mro_entry in get_mro(subtype):
        if mro_entry.__origin__ is cls.__origin__:
            mro_entry_parametrization = get_parametrization(mro_entry)
            cls_parametrization = get_parametrization(cls)
            sig = _get_generic_signature(cls)

            for orig_param in sig.__args__:
                param = orig_param
                if _has_origin(param) and param.__origin__ is Unpack:
                    (param,) = param.__args__

                mro_entry_args = mro_entry_parametrization[param]
                if not isinstance(mro_entry_args, tuple):
                    mro_entry_args = (mro_entry_args,)

                cls_args = cls_parametrization[param]
                if not isinstance(cls_args, tuple):
                    cls_args = (cls_args,)

                if not all(
                    map(
                        partial(_inner_type_check, param=param),
                        mro_entry_args,
                        cls_args,
                    ),
                ):
                    break
            else:
                return True
    return False