Skip to content

refs

Utilities for working with typing.ForwardRef.

This module allows the developer to create and evaluate typing.ForwardRef instances with additional logic to support forwards compatibility.

Typical Usage

>>> from typelib.py import refs
>>> ref = refs.forwardref("str")
>>> cls = refs.evaluate(ref)
>>> cls is str
True

forwardref

forwardref(ref: str | type, *, is_argument: bool = False, module: Any | None = None, is_class: bool = True) -> ForwardRef

Create a typing.ForwardRef instance from a ref string.

This wrapper function will attempt to determine the module name ahead of instantiation if not provided. This is important when resolving the reference to an actual type.

Parameters:

  • ref (str | type) –

    The type reference string.

  • is_argument (bool, default: False ) –

    Whether the reference string was an argument to a function (default False).

  • module (Any | None, default: None ) –

    The python module in which the reference string is defined (optional)

  • is_class (bool, default: True ) –

    Whether the reference string is a class (default True).

Source code in src/typelib/py/refs.py
def forwardref(
    ref: str | type,
    *,
    is_argument: bool = False,
    module: typing.Any | None = None,
    is_class: bool = True,
) -> ForwardRef:
    """Create a [`typing.ForwardRef`][] instance from a `ref` string.

    This wrapper function will attempt to determine the module name ahead of instantiation
    if not provided. This is important when resolving the reference to an actual type.

    Args:
        ref: The type reference string.
        is_argument: Whether the reference string was an argument to a function (default False).
        module: The python module in which the reference string is defined (optional)
        is_class: Whether the reference string is a class (default True).
    """
    if not isinstance(ref, str):
        name = inspection.qualname(ref)
        module = module or getattr(ref, "__module__", None)
    else:
        name = typing.cast(str, ref)

    module = _resolve_module_name(ref, module)
    if module is not None:
        name = name.replace(f"{module}.", "")

    return ForwardRef(
        name,
        is_argument=is_argument,
        module=module,
        is_class=is_class,
    )