Skip to content

markdown

Class info

🛈 DocStrings

Schema to Markdown conversion utilities.

instance_to_markdown

instance_to_markdown(
    instance: BaseModel,
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    include_values: bool = True,
    display_mode: OutputMode = "table",
    exclude_none: bool = False,
    exclude_defaults_yaml: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: HeaderStyle = "default",
    serialization_mode: SerializationMode = "json",
    mask_value: str | None = None,
    as_listitem: bool = True,
    wrapped_in: str | None = None
) -> str

Convert a Pydantic model instance to Markdown documentation.

When include_values is True, the current values are shown alongside defaults.

Parameters:

Name Type Description Default
instance BaseModel

The Pydantic model instance to document

required
template str | None

Custom Jinja2 template string

None
header_level int

Starting header level (1 = h1, 2 = h2, etc.)

1
include_defaults bool

Include default values in the table

True
include_examples bool

Include examples section

True
include_constraints bool

Include constraints section

True
include_values bool

Include current instance values

True
display_mode OutputMode

Output format - "table", "python_code", or "yaml"

'table'
exclude_none bool

Exclude None values from YAML

False
exclude_defaults_yaml bool

Exclude default values from YAML

False
exclude_unset bool

Exclude unset values from YAML

False
indent int

YAML indentation

2
header_style HeaderStyle

Code block header style - "default" or "pymdownx"

'default'
serialization_mode SerializationMode

Pydantic serialization mode - "json" (default) or "python"

'json'
mask_value str | None

Placeholder string to use for masked values. Defaults to "!ENV ENV_VAR_NAME"

None
as_listitem bool

Wrap the YAML config in a list (default: True)

True
wrapped_in str | None

Wrap the config in a dict with this key (default: None)

None

Returns:

Type Description
str

Markdown string documenting the model instance

Source code in src/schemez/markdown.py
def instance_to_markdown(
    instance: BaseModel,
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    include_values: bool = True,
    display_mode: OutputMode = "table",
    exclude_none: bool = False,
    exclude_defaults_yaml: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: HeaderStyle = "default",
    serialization_mode: SerializationMode = "json",
    mask_value: str | None = None,
    as_listitem: bool = True,
    wrapped_in: str | None = None,
) -> str:
    """Convert a Pydantic model instance to Markdown documentation.

    When include_values is True, the current values are shown alongside defaults.

    Args:
        instance: The Pydantic model instance to document
        template: Custom Jinja2 template string
        header_level: Starting header level (1 = h1, 2 = h2, etc.)
        include_defaults: Include default values in the table
        include_examples: Include examples section
        include_constraints: Include constraints section
        include_values: Include current instance values
        display_mode: Output format - "table", "python_code", or "yaml"
        exclude_none: Exclude None values from YAML
        exclude_defaults_yaml: Exclude default values from YAML
        exclude_unset: Exclude unset values from YAML
        indent: YAML indentation
        header_style: Code block header style - "default" or "pymdownx"
        serialization_mode: Pydantic serialization mode - "json" (default) or "python"
        mask_value: Placeholder string to use for masked values. Defaults to "!ENV ENV_VAR_NAME"
        as_listitem: Wrap the YAML config in a list (default: True)
        wrapped_in: Wrap the config in a dict with this key (default: None)

    Returns:
        Markdown string documenting the model instance
    """
    if display_mode == "python_code":
        model_class = type(instance)
        try:
            source = inspect.getsource(model_class)
            num_lines = len(source.splitlines())
            path = f"{model_class.__module__}.{model_class.__name__}"
            header = _format_code_header(
                path,
                1,
                num_lines,
                style=header_style,
                title=model_class.__name__,
                language="python",
            )
        except OSError:
            # Source code not available (e.g., dynamically created classes)
            path = f"{model_class.__module__}.{model_class.__name__}"
            header = _format_code_header(
                path, 1, 1, style=header_style, title=model_class.__name__, language="python"
            )
            return f"{header}\n# Source code not available for {model_class.__name__}\n```\n"
        else:
            return f"{header}\n{source}```\n"

    if display_mode == "yaml":
        import yamling

        from schemez.commented_yaml import process_yaml_lines

        yaml_data: dict[str, Any] | list[Any] = instance.model_dump(
            exclude_none=exclude_none,
            exclude_defaults=exclude_defaults_yaml,
            exclude_unset=exclude_unset,
            mode=serialization_mode,
        )

        # Filter out synthetic example_name field added by generator
        if isinstance(yaml_data, dict):
            yaml_data.pop("example_name", None)
            yaml_data.pop("example_name_", None)  # In case of collision

        # Apply wrapping options
        if as_listitem:
            yaml_data = [yaml_data]
        if wrapped_in:
            yaml_data = {wrapped_in: yaml_data}

        base_yaml = yamling.dump_yaml(
            yaml_data,
            sort_keys=False,
            indent=indent,
            default_flow_style=None,
            allow_unicode=True,
        )

        json_schema = instance.model_json_schema()
        yaml_lines = base_yaml.strip().split("\n")
        commented_lines = process_yaml_lines(yaml_lines, json_schema)
        yaml_content = "\n".join(commented_lines)
        # Build output with header and docstring
        model_class = type(instance)
        result_parts = []
        # Get model title from schema or use class name
        model_title = json_schema.get("x-doc-title", json_schema.get("title", model_class.__name__))
        # Add markdown header
        result_parts.append(f"{'#' * header_level} {model_title}\n\n")
        # Add class docstring if available
        if model_class.__doc__:
            docstring = inspect.cleandoc(model_class.__doc__)
            result_parts.append(f"{docstring}\n\n")

        # Add YAML code block
        path = f"{model_class.__module__}.{model_class.__name__}.yaml"
        header = _format_code_header(
            path,
            1,
            len(commented_lines),
            style=header_style,
            title=f"{model_title} (YAML)",
            language="yaml",
        )
        result_parts.append(f"{header}\n{yaml_content}\n```\n")

        return "".join(result_parts)

    # Default table mode
    result = model_to_markdown(
        type(instance),
        template=template,
        header_level=header_level,
        include_defaults=include_defaults,
        include_examples=include_examples,
        include_constraints=include_constraints,
        display_mode="table",
        header_style=header_style,
        mask_value=mask_value,
    )

    if include_values:
        values_md = f"\n{'#' * header_level} Current Values\n\n"
        values_md += "| Field | Value |\n|-------|-------|\n"
        for field_name, value in instance.model_dump().items():
            values_md += f"| `{field_name}` | `{_format_default(value)}` |\n"
        result = result.rstrip() + "\n" + values_md

    return result

model_to_markdown

model_to_markdown(
    model: type[BaseModel] | str,
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    display_mode: OutputMode = "table",
    mode: Literal["minimal", "maximal", "default"] = "default",
    exclude_none: bool = False,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: HeaderStyle = "default",
    serialization_mode: SerializationMode = "json",
    mask_value: str | None = None,
    as_listitem: bool = True,
    wrapped_in: str | None = None
) -> str

Convert a Pydantic model class to Markdown documentation.

Parameters:

Name Type Description Default
model type[BaseModel] | str

The Pydantic model class to document or import path string like 'module.path:ClassName' or 'module.path.ClassName'

required
template str | None

Custom Jinja2 template string (uses DEFAULT_TEMPLATE if None)

None
header_level int

Starting header level (1 = h1, 2 = h2, etc.)

1
include_defaults bool

Include default values in the table

True
include_examples bool

Include examples section

True
include_constraints bool

Include constraints section

True
display_mode OutputMode

Output format - "table", "python_code", or "yaml"

'table'
mode Literal['minimal', 'maximal', 'default']

Generation mode for YAML examples

'default'
exclude_none bool

Exclude None values from YAML

False
exclude_defaults bool

Exclude default values from YAML

False
exclude_unset bool

Exclude unset values from YAML

False
indent int

YAML indentation

2
header_style HeaderStyle

Code block header style - "default" or "pymdownx"

'default'
serialization_mode SerializationMode

Pydantic serialization mode - "json" (default) or "python"

'json'
mask_value str | None

Mask value for SecretStr objects

None
as_listitem bool

Wrap the YAML config in a list (default: True)

True
wrapped_in str | None

Wrap the config in a dict with this key (default: None)

None

Returns:

Type Description
str

Markdown string documenting the model

Source code in src/schemez/markdown.py
def model_to_markdown(
    model: type[BaseModel] | str,
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    display_mode: OutputMode = "table",
    mode: Literal["minimal", "maximal", "default"] = "default",
    exclude_none: bool = False,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: HeaderStyle = "default",
    serialization_mode: SerializationMode = "json",
    mask_value: str | None = None,
    as_listitem: bool = True,
    wrapped_in: str | None = None,
) -> str:
    """Convert a Pydantic model class to Markdown documentation.

    Args:
        model: The Pydantic model class to document or import path string
            like 'module.path:ClassName' or 'module.path.ClassName'
        template: Custom Jinja2 template string (uses DEFAULT_TEMPLATE if None)
        header_level: Starting header level (1 = h1, 2 = h2, etc.)
        include_defaults: Include default values in the table
        include_examples: Include examples section
        include_constraints: Include constraints section
        display_mode: Output format - "table", "python_code", or "yaml"
        mode: Generation mode for YAML examples
        exclude_none: Exclude None values from YAML
        exclude_defaults: Exclude default values from YAML
        exclude_unset: Exclude unset values from YAML
        indent: YAML indentation
        header_style: Code block header style - "default" or "pymdownx"
        serialization_mode: Pydantic serialization mode - "json" (default) or "python"
        mask_value: Mask value for SecretStr objects
        as_listitem: Wrap the YAML config in a list (default: True)
        wrapped_in: Wrap the config in a dict with this key (default: None)

    Returns:
        Markdown string documenting the model
    """
    import minijinja

    if isinstance(model, str):
        model = _resolve_model_from_import_path(model)

    if display_mode == "python_code":
        try:
            source = inspect.getsource(model)
            num_lines = len(source.splitlines())
            path = f"{model.__module__}.{model.__name__}"
            header = _format_code_header(
                path, 1, num_lines, style=header_style, title=model.__name__, language="python"
            )
        except OSError:
            # Source code not available (e.g., dynamically created classes)
            path = f"{model.__module__}.{model.__name__}"
            header = _format_code_header(
                path, 1, 1, style=header_style, title=model.__name__, language="python"
            )
            return f"{header}\n# Source code not available for {model.__name__}\n```\n"
        else:
            return f"{header}\n{source}```\n"

    if display_mode == "yaml":
        import yamling

        from schemez.commented_yaml import process_yaml_lines
        from schemez.generators import SchemaDataGenerator

        json_schema = model.model_json_schema()
        generator = SchemaDataGenerator(json_schema)

        if mode == "minimal":
            data = generator.generate_minimal()
        elif mode == "maximal":
            data = generator.generate_maximal()
        else:  # default
            data = generator.generate()

        try:
            instance = model.model_validate(data)
        except Exception:  # noqa: BLE001
            # Validation may fail due to constraints, fall back to model_construct
            instance = model.model_construct(**data)

        # Use 'python' mode to avoid SecretStr serialization issues
        yaml_data: dict[str, Any] | list[Any] = instance.model_dump(
            exclude_none=exclude_none,
            exclude_defaults=exclude_defaults,
            exclude_unset=exclude_unset,
            mode="python",
        )

        # Filter out synthetic example_name field added by generator
        if isinstance(yaml_data, dict):
            yaml_data.pop("example_name", None)
            yaml_data.pop("example_name_", None)  # In case of collision

        # Convert SecretStr objects to masked strings
        if isinstance(yaml_data, dict):
            yaml_data = _process_secret_str(yaml_data, model, mask_value=mask_value)

        # Apply wrapping options
        if as_listitem:
            yaml_data = [yaml_data]
        if wrapped_in:
            yaml_data = {wrapped_in: yaml_data}

        base_yaml = yamling.dump_yaml(
            yaml_data,
            sort_keys=False,
            indent=indent,
            default_flow_style=None,
            allow_unicode=True,
        )

        yaml_lines = base_yaml.strip().split("\n")
        commented_lines = process_yaml_lines(
            yaml_lines, json_schema, as_listitem=as_listitem, wrapped_in=wrapped_in
        )
        yaml_content = "\n".join(commented_lines)

        # Build output with header and docstring
        result_parts = []

        # Get model title from schema or use class name
        json_schema = model.model_json_schema()
        model_title = json_schema.get("x-doc-title", json_schema.get("title", model.__name__))

        # Add markdown header
        result_parts.append(f"{'#' * header_level} {model_title}\n\n")

        # Add class docstring if available
        if model.__doc__:
            docstring = inspect.cleandoc(model.__doc__)
            result_parts.append(f"{docstring}\n\n")

        # Add YAML code block
        path = f"{model.__module__}.{model.__name__}.yaml"
        header = _format_code_header(
            path,
            1,
            len(commented_lines),
            style=header_style,
            title=f"{model_title} (YAML)",
            language="yaml",
        )
        result_parts.append(f"{header}\n{yaml_content}\n```\n")

        return "".join(result_parts)

    # Default table mode
    context = schema_to_markdown_context(
        model,
        header_level=header_level,
        include_defaults=include_defaults,
        include_examples=include_examples,
        include_constraints=include_constraints,
    )

    env = minijinja.Environment(auto_escape_callback=lambda _name: None, pycompat=True)
    result = env.render_str(template or DEFAULT_TEMPLATE, **context).strip() + "\n"
    return _clean_markdown(result)

model_union_to_markdown

model_union_to_markdown(
    union_type: Any,
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    display_mode: OutputMode = "table",
    mode: Literal["minimal", "maximal", "default"] = "default",
    exclude_none: bool = False,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: HeaderStyle = "default",
    serialization_mode: SerializationMode = "json",
    mask_value: str | None = None,
    as_listitem: bool = True,
    wrapped_in: str | None = None
) -> str

Convert a Union type containing Pydantic models to Markdown documentation.

Runtime-inspects the Union and generates markdown for all included BaseModel types.

Parameters:

Name Type Description Default
union_type Any

A Union type containing Pydantic model classes or import path string like 'module.path:UnionAlias' or 'module.path.UnionAlias'

required
template str | None

Custom Jinja2 template string (uses DEFAULT_TEMPLATE if None)

None
header_level int

Starting header level (1 = h1, 2 = h2, etc.)

1
include_defaults bool

Include default values in the table

True
include_examples bool

Include examples section

True
include_constraints bool

Include constraints section

True
display_mode OutputMode

Output format - "table", "python_code", or "yaml"

'table'
mode Literal['minimal', 'maximal', 'default']

Generation mode for YAML examples

'default'
exclude_none bool

Exclude None values from YAML

False
exclude_defaults bool

Exclude default values from YAML

False
exclude_unset bool

Exclude unset values from YAML

False
indent int

YAML indentation

2
header_style HeaderStyle

Code block header style - "default" or "pymdownx"

'default'
serialization_mode SerializationMode

Pydantic serialization mode - "json" (default) or "python"

'json'
mask_value str | None

Placeholder string to use for masked values. Defaults to "!ENV ENV_VAR_NAME"

None
as_listitem bool

Wrap the YAML config in a list (default: True)

True
wrapped_in str | None

Wrap the config in a dict with this key (default: None)

None

Returns:

Type Description
str

Markdown string documenting all models in the union

Source code in src/schemez/markdown.py
def model_union_to_markdown(
    union_type: Any,  # type | str | types.UnionType | typing._SpecialForm,
    *,
    template: str | None = None,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
    display_mode: OutputMode = "table",
    mode: Literal["minimal", "maximal", "default"] = "default",
    exclude_none: bool = False,
    exclude_defaults: bool = False,
    exclude_unset: bool = False,
    indent: int = 2,
    header_style: HeaderStyle = "default",
    serialization_mode: SerializationMode = "json",
    mask_value: str | None = None,
    as_listitem: bool = True,
    wrapped_in: str | None = None,
) -> str:
    """Convert a Union type containing Pydantic models to Markdown documentation.

    Runtime-inspects the Union and generates markdown for all included BaseModel types.

    Args:
        union_type: A Union type containing Pydantic model classes or import path string
            like 'module.path:UnionAlias' or 'module.path.UnionAlias'
        template: Custom Jinja2 template string (uses DEFAULT_TEMPLATE if None)
        header_level: Starting header level (1 = h1, 2 = h2, etc.)
        include_defaults: Include default values in the table
        include_examples: Include examples section
        include_constraints: Include constraints section
        display_mode: Output format - "table", "python_code", or "yaml"
        mode: Generation mode for YAML examples
        exclude_none: Exclude None values from YAML
        exclude_defaults: Exclude default values from YAML
        exclude_unset: Exclude unset values from YAML
        indent: YAML indentation
        header_style: Code block header style - "default" or "pymdownx"
        serialization_mode: Pydantic serialization mode - "json" (default) or "python"
        mask_value: Placeholder string to use for masked values. Defaults to "!ENV ENV_VAR_NAME"
        as_listitem: Wrap the YAML config in a list (default: True)
        wrapped_in: Wrap the config in a dict with this key (default: None)

    Returns:
        Markdown string documenting all models in the union
    """
    # Resolve import path if string
    if isinstance(union_type, str):
        union_type = _resolve_from_import_path(union_type)

    # Unwrap Annotated if needed
    origin = get_origin(union_type)
    if origin is Annotated:
        # Get the actual type from Annotated[Union[...], ...]
        union_type = get_args(union_type)[0]
        origin = get_origin(union_type)

    # Check if it's a Union type
    if origin not in (Union, types.UnionType):  # Check if it's a Union
        msg = f"Expected Union type, got: {union_type}"
        raise TypeError(msg)

    # Get all types in the union
    union_args = get_args(union_type)

    # Filter for BaseModel classes
    model_classes = [
        i
        for i in union_args
        if inspect.isclass(i) and hasattr(i, "model_json_schema") and i is not type(None)
    ]

    if not model_classes:
        msg = f"No Pydantic BaseModel classes found in union: {union_type}"
        raise ValueError(msg)

    # Generate markdown for each model
    markdown_parts = []
    for model_class in model_classes:
        model_md = model_to_markdown(
            model_class,
            template=template,
            header_level=header_level,
            include_defaults=include_defaults,
            include_examples=include_examples,
            include_constraints=include_constraints,
            display_mode=display_mode,
            mode=mode,
            exclude_none=exclude_none,
            exclude_defaults=exclude_defaults,
            exclude_unset=exclude_unset,
            indent=indent,
            header_style=header_style,
            serialization_mode=serialization_mode,
            mask_value=mask_value,
            as_listitem=as_listitem,
            wrapped_in=wrapped_in,
        )
        markdown_parts.append(model_md)

    # Combine all markdown with separators
    if display_mode in ("python_code", "yaml"):
        result = "\n\n".join(markdown_parts)
    else:
        result = "\n\n---\n\n".join(markdown_parts)
    return _clean_markdown(result)

schema_to_markdown_context

schema_to_markdown_context(
    model: type[BaseModel],
    *,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True
) -> dict[str, Any]

Convert a Pydantic model to a Jinja2 template context.

Parameters:

Name Type Description Default
model type[BaseModel]

The Pydantic model class to convert

required
header_level int

Starting header level (1 = h1)

1
include_defaults bool

Include default values in output

True
include_examples bool

Include examples in output

True
include_constraints bool

Include constraints section

True

Returns:

Type Description
dict[str, Any]

Dictionary suitable for rendering with the markdown template

Source code in src/schemez/markdown.py
def schema_to_markdown_context(
    model: type[BaseModel],
    *,
    header_level: int = 1,
    include_defaults: bool = True,
    include_examples: bool = True,
    include_constraints: bool = True,
) -> dict[str, Any]:
    """Convert a Pydantic model to a Jinja2 template context.

    Args:
        model: The Pydantic model class to convert
        header_level: Starting header level (1 = h1)
        include_defaults: Include default values in output
        include_examples: Include examples in output
        include_constraints: Include constraints section

    Returns:
        Dictionary suitable for rendering with the markdown template
    """
    schema = model.model_json_schema()
    defs = schema.get("$defs", {})

    # Build model path for the root model
    model_path = f"{model.__module__}.{model.__qualname__}"
    root = _extract_model_info(model.__name__, schema, defs, model_path=model_path)

    nested_models: dict[str, dict[str, Any]] = {}
    for def_name, def_schema in defs.items():
        nested_models[def_name] = _extract_model_info(def_name, def_schema, defs)

    return {
        "root": root,
        "nested_models": nested_models,
        "header_level": header_level,
        "include_defaults": include_defaults,
        "include_examples": include_examples,
        "include_constraints": include_constraints,
    }

setup_jinjarope_filters

setup_jinjarope_filters(env: Any) -> None

Set up schemez markdown filters for jinjarope.

This function is used as an entry point for the jinjarope.environment extension group to add markdown-related filters to Jinja2 environments.

Parameters:

Name Type Description Default
env Any

The Jinja2 environment to modify

required
Source code in src/schemez/markdown.py
def setup_jinjarope_filters(env: Any) -> None:
    """Set up schemez markdown filters for jinjarope.

    This function is used as an entry point for the jinjarope.environment
    extension group to add markdown-related filters to Jinja2 environments.

    Args:
        env: The Jinja2 environment to modify
    """
    # Add filters to the environment
    env.filters["schema_to_markdown"] = model_to_markdown
    env.filters["instance_to_markdown"] = instance_to_markdown
    env.filters["union_to_markdown"] = model_union_to_markdown