Typing Stubs for PyYAML

6.0.12.20250915 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

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`.

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.

view raw JSON →