This package provides static type annotations (stubs) for the PyYAML library. PyYAML is a full-featured YAML parser and emitter for Python, enabling seamless interaction with YAML data for configurations and structured data. Types-PyYAML allows static type checkers like mypy and pyright to analyze code using PyYAML, improving code quality and catching potential type errors before runtime. This package is part of the typeshed project and aims to provide accurate annotations for PyYAML versions 6.0.*.
pip install types-PyYAMLVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how `types-PyYAML` enables static type checking for `PyYAML` code using `mypy`. After installing `PyYAML`, `types-PyYAML`, and `mypy`, save the code to `app.py` and run `mypy app.py`. Mypy will detect the deliberate type error where an integer is assigned to a key expected to hold a string, thanks to the type information provided by `types-PyYAML`.
Consider pinning your `types-PyYAML` version in your `requirements.txt` (e.g., `types-PyYAML==6.0.12.20250915`) and regularly testing updates. You can also temporarily ignore specific errors using `type: ignore` comments if a stub change is overly strict or controversial, while contributing fixes to typeshed.
If strict type checking is desired, you may need to use `typing.cast` or `type: ignore` to suppress these specific errors. Alternatively, structure your code to use a single `Loader`/`Dumper` definition to avoid type checker confusion, or refactor to reduce direct exposure of the `Loader` type.
Be aware of YAML 1.1's implicit typing rules when writing or consuming YAML files with PyYAML. For stricter YAML 1.2 compliance, consider alternative libraries like `ruamel.yaml` if the `types-PyYAML` stubs' accuracy for PyYAML's behavior is undesirable for your use case.
It is recommended to explicitly install both `PyYAML` and `types-PyYAML` and to regularly update both, while ensuring their compatibility. Typeshed recommends either using the same version bounds for stubs as for the package or pinning the stubs to a known good version.