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.
pip install eval-type-backportVerified import paths — ran on the pinned version, not inferred.
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()`.
Consider if you truly need to evaluate types at runtime for compatibility; often, simply upgrading your Python version or using `typing.Union`/`typing.List` directly is more appropriate for application code.
Install `eval-type-backport` and ensure libraries evaluating your type hints are configured to use it, or explicitly use older `typing` constructs (e.g., `typing.Union[X, Y]`, `typing.List[X]`), or upgrade to a Python version that natively supports these features.
Upgrade your project's Python version to 3.10 or newer to remove the need for this backport for common modern syntax.
Ensure `from __future__ import annotations` is the absolute first executable statement in your Python script, immediately after the shebang (if present) and encoding declaration (if present), and before any other code or comments.
Install the `eval-type-backport` package: `pip install eval-type-backport`. Ensure any libraries that rely on it (like Pydantic) are also updated to versions that correctly leverage this backport. Alternatively, manually replace `X | Y` with `typing.Union[X, Y]` and `list[X]` with `typing.List[X]` in your code.
Upgrade `eval-type-backport` to its latest version (`pip install --upgrade eval-type-backport`) to ensure you have the most recent compatibility fixes. If the problem persists, ensure `ClassVar` is explicitly typed (e.g., `MY_CLASS_CONSTANT: ClassVar[int] = 5`) as some contexts might require clearer annotations for evaluation.
Install the package using pip: `pip install eval-type-backport`. Verify that you are running Python from the correct environment (e.g., a virtual environment) where the package was installed.