eval-type-backport

0.3.1 · active · verified Sun Mar 29

Like `typing._eval_type`, this tiny package provides a replacement to support newer typing features (such as `X | Y` for unions from PEP 604 and `list[X]` for generic built-ins from PEP 585) in older Python versions (>=3.7). It allows libraries like Pydantic to maintain modern type hint syntax while supporting a wider range of Python environments. It is currently at version 0.3.1 and sees updates as needed for compatibility.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `eval_type_backport` to resolve a modern type hint like `str | None`. This function is typically used internally by other libraries (like Pydantic) to provide compatibility for newer Python typing features on older Python versions. The `globalns` and `localns` arguments provide the context for evaluating the type string, similar to `eval()`.

import sys
from __future__ import annotations

from eval_type_backport import eval_type_backport

class MyModel:
    field: str | None

def demonstrate_eval(cls):
    # Simulate a scenario where `str | None` might not be directly evaluable
    # e.g., on Python < 3.10 without __future__.annotations, or in certain contexts.
    # The backport ensures it resolves to typing.Union[str, None].
    # For this example, we're just showing the direct usage of the function.
    
    # Get the annotation for 'field'
    annotation = cls.__annotations__['field']
    
    # Evaluate it using the backport function
    evaluated_type = eval_type_backport(annotation, globalns=sys.modules[__name__].__dict__, localns={})
    
    print(f"Original annotation: {annotation!r}")
    print(f"Evaluated type: {evaluated_type!r}")

if __name__ == "__main__":
    demonstrate_eval(MyModel)

view raw JSON →