.. PEP: 9999
.. Title: Optional Runtime Enforcement of Type Annotations
.. Author: Karlos karlos.santana13@gmail.com
.. Status: Draft
.. Type: Standards Track
.. Content-Type: text/x-rst
.. Created: 2024-05-26
Abstract
This PEP proposes adding an optional mechanism to enforce type annotations
at runtime in Python, enabling developers to opt-in to stricter typing behavior
when desired.
Motivation
Python’s type hints (PEP 484 and related) are currently used for static
analysis and documentation, but they are not enforced at runtime. This leads to
the following issues:
- Developers expect type hints to be respected, but Python still accepts values of any type.
- Bugs caused by incorrect types (e.g., passing a
bool
whereint
is expected) are silently ignored. - Existing runtime type checkers (like
typeguard
andbeartype
) are external and inconsistent.
This PEP aims to make type annotations optionally enforceable by the interpreter or via a standard decorator.
Specification
We propose two mechanisms for enabling runtime type enforcement:
-
Decorator-based Enforcement
Introduce a new decorator in the standard library:
.. code-block:: python
from typing_enforce import enforce_types @enforce_types def greet(name: str, times: int) -> None: print(("Hello, " + name) * times) greet("World", 3) # OK greet("World", "three") # TypeError
-
Interpreter Flag (Optional)
Add a new interpreter flag:
.. code-block:: bash
python -X enforce-types script.py
When enabled, all function calls with annotations will check argument types and return values
against their annotations. Violations will raiseTypeError
.
Backwards Compatibility
This feature is opt-in. Existing codebases will not be affected unless they explicitly enable it.
Reference Implementation
Prototype decorators already exist in third-party libraries:
typeguard
beartype
This PEP proposes adapting a simplified version of such behavior for inclusion in the standard library.
Rejected Ideas
- Mandatory enforcement: Too disruptive; not Pythonic.
- Postponed evaluation only: Doesn’t address runtime safety.
Copyright
This document has been placed in the public domain.