Typing Stubs for PyYAML
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.*.
Warnings
- breaking Updates to type stubs, even without changes to your runtime code, can introduce new type-checking errors. This is because typeshed aims to improve the accuracy of type annotations, which might expose previously unflagged type inconsistencies in your codebase.
- gotcha When attempting to use the C-accelerated `CLoader` or `CDumper` from PyYAML with a fallback to pure Python `Loader`/`Dumper`, type checkers like mypy can report `Incompatible import` errors. This happens because `CLoader` and `Loader` are distinct types, even though they often serve a similar purpose.
- gotcha PyYAML (and thus its stubs) is based on the older YAML 1.1 specification. This can lead to unexpected implicit type conversions (e.g., 'yes', 'no' become booleans; '010' becomes an octal integer; `59:59` interpreted as seconds) compared to the stricter YAML 1.2 specification common in other parsers. The stubs accurately reflect these 1.1 behaviors.
- gotcha The versioning of `types-PyYAML` is independent of `PyYAML` itself, though the stubs target specific `PyYAML` versions (e.g., `types-PyYAML 6.0.x.YYYYMMDD` targets `PyYAML==6.0.*`). This means updating one does not automatically update the other, and an older stub version might not fully cover a newer PyYAML, or vice versa.
Install
-
pip install types-PyYAML -
pip install PyYAML types-PyYAML mypy
Imports
- yaml
import yaml
- load, dump
from yaml import load, dump
Quickstart
import yaml
from typing import Any
def process_config(config_str: str) -> dict[str, Any]:
data: dict[str, Any] = yaml.safe_load(config_str)
# Introduce a deliberate type error for demonstration
# 'name' is expected to be a string, but we assign a number
# mypy should flag this if types-PyYAML is correctly used.
if 'name' in data: # type: ignore[reportUntypedBaseMembers]
data['name'] = 123 # Intentionally wrong type for demo
return data
config_data = """
name: Alice
age: 30
"""
# This would normally be executed, but the focus is on static analysis
# processed_data = process_config(config_data)
# print(processed_data)
# To run mypy and see the type error:
# 1. pip install PyYAML types-PyYAML mypy
# 2. Save this code as `app.py`
# 3. Run: `mypy app.py`
# Expected output should include a type error about data['name'] assignment.