Skip to content

schema

Class info

Classes

Name Children Inherits
ConfigSchema
schemez.schema
Schema for configuration objects that may declare required packages.
    Schema
    schemez.schema
    Base class for configuration models.

    🛈 DocStrings

    Configuration models for Schemez.

    ConfigSchema

    Bases: Schema

    Schema for configuration objects that may declare required packages.

    Source code in src/schemez/schema.py
    class ConfigSchema(Schema):
        """Schema for configuration objects that may declare required packages."""
    
        @classmethod
        def required_python_packages(cls) -> list[str]:
            """Return the Python packages this config needs. Override in subclasses."""
            return []
    

    required_python_packages classmethod

    required_python_packages() -> list[str]
    

    Return the Python packages this config needs. Override in subclasses.

    Source code in src/schemez/schema.py
    @classmethod
    def required_python_packages(cls) -> list[str]:
        """Return the Python packages this config needs. Override in subclasses."""
        return []
    

    Inner

    Bases: Schema

    A nested model for demonstration.

    Source code in src/schemez/schema.py
    class Inner(Schema):
        """A nested model for demonstration."""
    
        a: int = 0
        """Inner class field"""
    

    a class-attribute instance-attribute

    a: int = 0
    

    Inner class field

    Outer

    Bases: Schema

    An outer model with nested schema.

    Source code in src/schemez/schema.py
    class Outer(Schema):
        """An outer model with nested schema."""
    
        b: str = Field(default="", examples=["hello"])
        """Outer string field."""
        inner: Inner | None = Field(default=None, examples=[{"a": 100}])
        """Outer nested field"""
    

    b class-attribute instance-attribute

    b: str = Field(default='', examples=['hello'])
    

    Outer string field.

    inner class-attribute instance-attribute

    inner: Inner | None = Field(default=None, examples=[{'a': 100}])
    

    Outer nested field

    Schema

    Bases: BaseModel

    Base class for configuration models.

    Provides: - Common Pydantic settings (extra="forbid", attribute docstrings as descriptions) - YAML loading and dumping (optionally with field descriptions as comments) - Markdown documentation, Python code and test data generation - Model creation from functions, class constructors and JSON Schema - Merging and sub-model iteration

    Dumps (model_dump(), model_dump_json(), YAML) put the fields of the most derived class first, then those of its bases. Pydantic itself orders base fields first, so a wrap serializer reorders the keys of every dump, nested Schema instances included. That makes dumps about 3x slower than a plain BaseModel (around 1.8 µs instead of 0.6 µs for a three-field model). This is deliberate: the order is what users read in dumped configs; the key order per class is cached, the remaining cost is the Python-level serializer call.

    Source code in src/schemez/schema.py
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    class Schema(BaseModel):
        """Base class for configuration models.
    
        Provides:
        - Common Pydantic settings (`extra="forbid"`, attribute docstrings as descriptions)
        - YAML loading and dumping (optionally with field descriptions as comments)
        - Markdown documentation, Python code and test data generation
        - Model creation from functions, class constructors and JSON Schema
        - Merging and sub-model iteration
    
        Dumps (`model_dump()`, `model_dump_json()`, YAML) put the fields of the most derived
        class first, then those of its bases. Pydantic itself orders base fields first, so a
        wrap serializer reorders the keys of every dump, nested `Schema` instances included.
        That makes dumps about 3x slower than a plain `BaseModel` (around 1.8 µs instead of
        0.6 µs for a three-field model). This is deliberate: the order is what users read in
        dumped configs; the key order per class is cached, the remaining cost is the Python-level
        serializer call.
        """
    
        model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    
        @model_serializer(mode="wrap")
        def _serialize_with_subclass_fields_first(self, serializer: Any, info: Any) -> dict[str, Any]:
            """Serialize with subclass fields appearing before base class fields.
    
            Only reorders: keys without a known rank (computed fields, extras) keep their
            place after the fields, and aliases rank like the field they belong to.
            """
            data = serializer(self)
            # A nested field holding a plain dict (model_construct) is passed in as `self`
            if not isinstance(data, dict) or not isinstance(self, BaseModel):
                return data
            rank = _key_rank(type(self))
            end = len(rank)
            return {k: data[k] for k in sorted(data, key=lambda k: rank.get(k, end))}
    
        def model_dump_markdown(
            self,
            *,
            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: Literal["table", "python_code", "yaml"] = "table",
            exclude_none: bool = True,
            exclude_defaults_yaml: bool = False,
            exclude_unset: bool = False,
            indent: int = 2,
            header_style: Literal["default", "pymdownx"] = "default",
            serialization_mode: Literal["json", "python"] = "json",
        ) -> str:
            """Dump model instance to Markdown documentation.
    
            Args:
                template: Custom Jinja2 template string (uses default 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
                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"
    
            Returns:
                Markdown string documenting the model
            """
            from schemez.markdown import instance_to_markdown
    
            return instance_to_markdown(
                self,
                template=template,
                header_level=header_level,
                include_defaults=include_defaults,
                include_examples=include_examples,
                include_constraints=include_constraints,
                include_values=include_values,
                display_mode=display_mode,
                exclude_none=exclude_none,
                exclude_defaults_yaml=exclude_defaults_yaml,
                exclude_unset=exclude_unset,
                indent=indent,
                header_style=header_style,
                serialization_mode=serialization_mode,
            )
    
        @classmethod
        def dump_markdown_schema(
            cls,
            *,
            template: str | None = None,
            header_level: int = 1,
            include_defaults: bool = True,
            include_examples: bool = True,
            include_constraints: bool = True,
            display_mode: Literal["table", "python_code", "yaml"] = "table",
            mode: Literal["minimal", "maximal", "default"] = "default",
            exclude_none: bool = True,
            exclude_defaults: bool = False,
            exclude_unset: bool = False,
            indent: int = 2,
            header_style: Literal["default", "pymdownx"] = "default",
            serialization_mode: Literal["json", "python"] = "json",
        ) -> str:
            """Dump model class schema to Markdown documentation.
    
            Args:
                template: Custom Jinja2 template string (uses default 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"
    
            Returns:
                Markdown string documenting the model schema
            """
            from schemez.markdown import model_to_markdown
    
            return model_to_markdown(
                cls,
                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,
            )
    
        def merge(self, other: Self) -> Self:
            """Merge with another instance by overlaying its non-None values."""
            from schemez.helpers import merge_models
    
            return merge_models(self, other)
    
        def iter_submodels(self, *, recursive: bool = True) -> Iterator[tuple[str, BaseModel]]:
            """Iterate through all nested BaseModel instances in fields.
    
            Supports fields of type:
            - BaseModel (direct instance)
            - list[BaseModel]
            - dict[str, BaseModel]
    
            Args:
                recursive: If True, also iterate through submodels of submodels
    
            Yields:
                Tuples of (path, submodel) where path is like "field", "field[0]", "field['key']"
            """
            return _iter_submodels(self, recursive=recursive)
    
        @classmethod
        def iter_submodel_types(
            cls, *, recursive: bool = True, include_union_members: bool = True
        ) -> Iterator[tuple[str, type[BaseModel]]]:
            """Iterate through all nested BaseModel types in field annotations.
    
            Supports field types:
            - BaseModel (direct type)
            - list[BaseModel]
            - dict[str, BaseModel]
            - BaseModel | OtherModel (unions, when include_union_members=True)
    
            Args:
                recursive: If True, also iterate through submodel types of submodels
                include_union_members: If True, yield each union member separately
    
            Yields:
                Tuples of (path, model_type) where path is like "field", "field[]", "field{}"
            """
            return _iter_submodel_types(
                cls, recursive=recursive, include_union_members=include_union_members
            )
    
        @classmethod
        def from_yaml(cls, content: str, inherit_path: JoinablePathLike | None = None) -> Self:
            """Create from YAML string."""
            import yamling
    
            data = yamling.load_yaml(content, resolve_inherit=inherit_path or False)
            return cls.model_validate(data)
    
        @classmethod
        def for_function(cls, func: Callable[..., Any], *, name: str | None = None) -> type[Schema]:
            """Create a schema model from a function's signature.
    
            Args:
                func: The function to create a schema from
                name: Optional name for the model
    
            Returns:
                A new schema model class based on the function parameters
            """
            from schemez.convert import get_function_model
    
            return get_function_model(func, name=name)
    
        @classmethod
        def from_json_schema(cls, json_schema: dict[str, Any]) -> type[Schema]:
            """Create a schema model from a JSON schema.
    
            Args:
                json_schema: The JSON schema to create a schema from
    
            Returns:
                A new schema model class based on the JSON schema
            """
            from schemez.schema_to_type import json_schema_to_pydantic_class
    
            return json_schema_to_pydantic_class(
                json_schema, class_name="GeneratedSchema", base_class=cls
            )
    
        @classmethod
        async def from_llm(
            cls,
            *prompts: JoinablePathLike | str | UserContent,
            model: str = "google-gla:gemini-2.0-flash",
            system_prompt: str = DEFAULT_SYSTEM_PROMPT,
            user_prompt: str = DEFAULT_USER_PROMPT,
        ) -> Self:
            """Create a schema model from a text snippet using AI.
    
            Args:
                prompts: The text to create a schema from
                model: The AI model to use for schema extraction
                system_prompt: The system prompt to use for schema extraction
                user_prompt: The user prompt to use for schema extraction
    
            Returns:
                A new schema model class based on the document
            """
            from agentpool import Agent
    
            prompt = system_prompt.format(name=cls.__name__)
            agent = Agent(model=model, system_prompt=prompt, output_type=cls)
            chat_message = await agent.run(user_prompt, prompts)
            return chat_message.content
    
        @classmethod
        def for_class_ctor(cls, target_cls: type) -> type[Schema]:
            """Create a schema model from a class constructor.
    
            Args:
                target_cls: The class whose constructor to convert
    
            Returns:
                A new schema model class based on the constructor parameters
            """
            from schemez.convert import get_ctor_basemodel
    
            return get_ctor_basemodel(target_cls)
    
        def model_dump_yaml(
            self,
            exclude_none: bool = True,
            exclude_defaults: bool = False,
            exclude_unset: bool = False,
            indent: int = 2,
            default_flow_style: bool | None = None,
            allow_unicode: bool = True,
            comments: bool = False,
            sort_keys: bool = True,
            mode: Literal["json", "python"] = "python",
        ) -> str:
            """Dump configuration to YAML string.
    
            Args:
                exclude_none: Exclude fields with None values
                exclude_defaults: Exclude fields with default values
                exclude_unset: Exclude fields that are not set
                indent: Indentation level for YAML output
                default_flow_style: Default flow style for YAML output
                allow_unicode: Allow unicode characters in YAML output
                comments: Include descriptions as comments in the YAML output
                sort_keys: Sort keys in the YAML output
                mode: Output mode, either "json" or "python"
    
            Returns:
                YAML string representation of the model
            """
            import yamling
    
            from schemez.commented_yaml import process_yaml_lines
    
            data = self.model_dump(
                exclude_none=exclude_none,
                exclude_defaults=exclude_defaults,
                exclude_unset=exclude_unset,
                mode=mode,
            )
            base_yaml = yamling.dump_yaml(
                data,
                sort_keys=sort_keys,
                indent=indent,
                default_flow_style=default_flow_style,
                allow_unicode=allow_unicode,
            )
            if not comments:
                return base_yaml
    
            schema = self.model_json_schema()
            yaml_lines = base_yaml.strip().split("\n")
            commented_lines = process_yaml_lines(yaml_lines, schema, as_listitem=False, wrapped_in=None)
    
            return "\n".join(commented_lines)
    
        def save(self, path: JoinablePathLike, overwrite: bool = False) -> None:
            """Save configuration to a YAML file.
    
            Args:
                path: Path to save the configuration to
                overwrite: Whether to overwrite an existing file
    
            Raises:
                OSError: If file cannot be written
                ValueError: If path is invalid
            """
            yaml_str = self.model_dump_yaml()
            try:
                file_path = upath.UPath(path)
                if file_path.exists() and not overwrite:
                    msg = f"File already exists: {path}"
                    raise FileExistsError(msg)  # noqa: TRY301
                file_path.parent.mkdir(parents=True, exist_ok=True)
                file_path.write_text(yaml_str)
            except Exception as exc:
                msg = f"Failed to save configuration to {path}"
                raise ValueError(msg) from exc
    
        @classmethod
        def to_python_code(
            cls,
            *,
            class_name: str | None = None,
            target_python_version: PythonVersionStr | None = None,
            model_type: str = "pydantic.BaseModel",
        ) -> str:
            """Convert this model to Python code asynchronously.
    
            Args:
                class_name: Optional custom class name for the generated code
                target_python_version: Target Python version for code generation
                model_type: Type of model to generate
    
            Returns:
                Generated Python code as string
            """
            return model_to_python_code(
                cls,
                class_name=class_name,
                target_python_version=target_python_version,
                model_type=model_type,
            )
    
        @classmethod
        def generate_test_data(
            cls,
            *,
            seed: int = 0,
            mode: Literal["minimal", "maximal", "default"] = "default",
            validate: bool = True,
        ) -> Self:
            """Generate test data that conforms to this schema.
    
            Args:
                seed: Seed for deterministic generation (default: 0)
                mode: Generation mode:
                    - "minimal": Only required fields, minimum values
                    - "maximal": All fields, maximum reasonable values
                    - "default": Balanced generation (default)
                validate: Whether to validate the generated data (default: True)
    
            Returns:
                An instance of this schema populated with generated test data
    
            Example:
                ```python
                class PersonSchema(Schema):
                    name: str
                    age: int = 25
                    email: str | None = None
    
                # Generate test data
                person = PersonSchema.generate_test_data(seed=42)
                # Result: PersonSchema(name="abc", age=42, email=None)
    
                # Generate minimal data (required fields only)
                minimal = PersonSchema.generate_test_data(mode="minimal")
                # Result: PersonSchema(name="a", age=0, email=None)
    
                # Generate maximal data (all fields populated)
                maximal = PersonSchema.generate_test_data(mode="maximal")
                # Result: PersonSchema(name="abcdefghij", age=1000, email="user0@example.com")
                ```
            """
            json_schema = cls.model_json_schema()
            generator = SchemaDataGenerator(json_schema, seed=seed)
    
            if mode == "minimal":
                data = generator.generate_minimal()
            elif mode == "maximal":
                data = generator.generate_maximal()
            else:  # default
                data = generator.generate()
    
            if validate:
                return cls.model_validate(data)
            return cls.model_construct(**data)
    

    dump_markdown_schema classmethod

    dump_markdown_schema(
        *,
        template: str | None = None,
        header_level: int = 1,
        include_defaults: bool = True,
        include_examples: bool = True,
        include_constraints: bool = True,
        display_mode: Literal["table", "python_code", "yaml"] = "table",
        mode: Literal["minimal", "maximal", "default"] = "default",
        exclude_none: bool = True,
        exclude_defaults: bool = False,
        exclude_unset: bool = False,
        indent: int = 2,
        header_style: Literal["default", "pymdownx"] = "default",
        serialization_mode: Literal["json", "python"] = "json"
    ) -> str
    

    Dump model class schema to Markdown documentation.

    Parameters:

    Name Type Description Default
    template str | None

    Custom Jinja2 template string (uses default 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 Literal['table', 'python_code', 'yaml']

    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

    True
    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 Literal['default', 'pymdownx']

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

    'default'
    serialization_mode Literal['json', 'python']

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

    'json'

    Returns:

    Type Description
    str

    Markdown string documenting the model schema

    Source code in src/schemez/schema.py
    @classmethod
    def dump_markdown_schema(
        cls,
        *,
        template: str | None = None,
        header_level: int = 1,
        include_defaults: bool = True,
        include_examples: bool = True,
        include_constraints: bool = True,
        display_mode: Literal["table", "python_code", "yaml"] = "table",
        mode: Literal["minimal", "maximal", "default"] = "default",
        exclude_none: bool = True,
        exclude_defaults: bool = False,
        exclude_unset: bool = False,
        indent: int = 2,
        header_style: Literal["default", "pymdownx"] = "default",
        serialization_mode: Literal["json", "python"] = "json",
    ) -> str:
        """Dump model class schema to Markdown documentation.
    
        Args:
            template: Custom Jinja2 template string (uses default 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"
    
        Returns:
            Markdown string documenting the model schema
        """
        from schemez.markdown import model_to_markdown
    
        return model_to_markdown(
            cls,
            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,
        )
    

    for_class_ctor classmethod

    for_class_ctor(target_cls: type) -> type[Schema]
    

    Create a schema model from a class constructor.

    Parameters:

    Name Type Description Default
    target_cls type

    The class whose constructor to convert

    required

    Returns:

    Type Description
    type[Schema]

    A new schema model class based on the constructor parameters

    Source code in src/schemez/schema.py
    @classmethod
    def for_class_ctor(cls, target_cls: type) -> type[Schema]:
        """Create a schema model from a class constructor.
    
        Args:
            target_cls: The class whose constructor to convert
    
        Returns:
            A new schema model class based on the constructor parameters
        """
        from schemez.convert import get_ctor_basemodel
    
        return get_ctor_basemodel(target_cls)
    

    for_function classmethod

    for_function(func: Callable[..., Any], *, name: str | None = None) -> type[Schema]
    

    Create a schema model from a function's signature.

    Parameters:

    Name Type Description Default
    func Callable[..., Any]

    The function to create a schema from

    required
    name str | None

    Optional name for the model

    None

    Returns:

    Type Description
    type[Schema]

    A new schema model class based on the function parameters

    Source code in src/schemez/schema.py
    @classmethod
    def for_function(cls, func: Callable[..., Any], *, name: str | None = None) -> type[Schema]:
        """Create a schema model from a function's signature.
    
        Args:
            func: The function to create a schema from
            name: Optional name for the model
    
        Returns:
            A new schema model class based on the function parameters
        """
        from schemez.convert import get_function_model
    
        return get_function_model(func, name=name)
    

    from_json_schema classmethod

    from_json_schema(json_schema: dict[str, Any]) -> type[Schema]
    

    Create a schema model from a JSON schema.

    Parameters:

    Name Type Description Default
    json_schema dict[str, Any]

    The JSON schema to create a schema from

    required

    Returns:

    Type Description
    type[Schema]

    A new schema model class based on the JSON schema

    Source code in src/schemez/schema.py
    @classmethod
    def from_json_schema(cls, json_schema: dict[str, Any]) -> type[Schema]:
        """Create a schema model from a JSON schema.
    
        Args:
            json_schema: The JSON schema to create a schema from
    
        Returns:
            A new schema model class based on the JSON schema
        """
        from schemez.schema_to_type import json_schema_to_pydantic_class
    
        return json_schema_to_pydantic_class(
            json_schema, class_name="GeneratedSchema", base_class=cls
        )
    

    from_llm async classmethod

    from_llm(
        *prompts: JoinablePathLike | str | UserContent,
        model: str = "google-gla:gemini-2.0-flash",
        system_prompt: str = DEFAULT_SYSTEM_PROMPT,
        user_prompt: str = DEFAULT_USER_PROMPT
    ) -> Self
    

    Create a schema model from a text snippet using AI.

    Parameters:

    Name Type Description Default
    prompts JoinablePathLike | str | UserContent

    The text to create a schema from

    ()
    model str

    The AI model to use for schema extraction

    'google-gla:gemini-2.0-flash'
    system_prompt str

    The system prompt to use for schema extraction

    DEFAULT_SYSTEM_PROMPT
    user_prompt str

    The user prompt to use for schema extraction

    DEFAULT_USER_PROMPT

    Returns:

    Type Description
    Self

    A new schema model class based on the document

    Source code in src/schemez/schema.py
    @classmethod
    async def from_llm(
        cls,
        *prompts: JoinablePathLike | str | UserContent,
        model: str = "google-gla:gemini-2.0-flash",
        system_prompt: str = DEFAULT_SYSTEM_PROMPT,
        user_prompt: str = DEFAULT_USER_PROMPT,
    ) -> Self:
        """Create a schema model from a text snippet using AI.
    
        Args:
            prompts: The text to create a schema from
            model: The AI model to use for schema extraction
            system_prompt: The system prompt to use for schema extraction
            user_prompt: The user prompt to use for schema extraction
    
        Returns:
            A new schema model class based on the document
        """
        from agentpool import Agent
    
        prompt = system_prompt.format(name=cls.__name__)
        agent = Agent(model=model, system_prompt=prompt, output_type=cls)
        chat_message = await agent.run(user_prompt, prompts)
        return chat_message.content
    

    from_yaml classmethod

    from_yaml(content: str, inherit_path: JoinablePathLike | None = None) -> Self
    

    Create from YAML string.

    Source code in src/schemez/schema.py
    @classmethod
    def from_yaml(cls, content: str, inherit_path: JoinablePathLike | None = None) -> Self:
        """Create from YAML string."""
        import yamling
    
        data = yamling.load_yaml(content, resolve_inherit=inherit_path or False)
        return cls.model_validate(data)
    

    generate_test_data classmethod

    generate_test_data(
        *,
        seed: int = 0,
        mode: Literal["minimal", "maximal", "default"] = "default",
        validate: bool = True
    ) -> Self
    

    Generate test data that conforms to this schema.

    Parameters:

    Name Type Description Default
    seed int

    Seed for deterministic generation (default: 0)

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

    Generation mode: - "minimal": Only required fields, minimum values - "maximal": All fields, maximum reasonable values - "default": Balanced generation (default)

    'default'
    validate bool

    Whether to validate the generated data (default: True)

    True

    Returns:

    Type Description
    Self

    An instance of this schema populated with generated test data

    Example
    class PersonSchema(Schema):
        name: str
        age: int = 25
        email: str | None = None
    
    # Generate test data
    person = PersonSchema.generate_test_data(seed=42)
    # Result: PersonSchema(name="abc", age=42, email=None)
    
    # Generate minimal data (required fields only)
    minimal = PersonSchema.generate_test_data(mode="minimal")
    # Result: PersonSchema(name="a", age=0, email=None)
    
    # Generate maximal data (all fields populated)
    maximal = PersonSchema.generate_test_data(mode="maximal")
    # Result: PersonSchema(name="abcdefghij", age=1000, email="user0@example.com")
    
    Source code in src/schemez/schema.py
    @classmethod
    def generate_test_data(
        cls,
        *,
        seed: int = 0,
        mode: Literal["minimal", "maximal", "default"] = "default",
        validate: bool = True,
    ) -> Self:
        """Generate test data that conforms to this schema.
    
        Args:
            seed: Seed for deterministic generation (default: 0)
            mode: Generation mode:
                - "minimal": Only required fields, minimum values
                - "maximal": All fields, maximum reasonable values
                - "default": Balanced generation (default)
            validate: Whether to validate the generated data (default: True)
    
        Returns:
            An instance of this schema populated with generated test data
    
        Example:
            ```python
            class PersonSchema(Schema):
                name: str
                age: int = 25
                email: str | None = None
    
            # Generate test data
            person = PersonSchema.generate_test_data(seed=42)
            # Result: PersonSchema(name="abc", age=42, email=None)
    
            # Generate minimal data (required fields only)
            minimal = PersonSchema.generate_test_data(mode="minimal")
            # Result: PersonSchema(name="a", age=0, email=None)
    
            # Generate maximal data (all fields populated)
            maximal = PersonSchema.generate_test_data(mode="maximal")
            # Result: PersonSchema(name="abcdefghij", age=1000, email="user0@example.com")
            ```
        """
        json_schema = cls.model_json_schema()
        generator = SchemaDataGenerator(json_schema, seed=seed)
    
        if mode == "minimal":
            data = generator.generate_minimal()
        elif mode == "maximal":
            data = generator.generate_maximal()
        else:  # default
            data = generator.generate()
    
        if validate:
            return cls.model_validate(data)
        return cls.model_construct(**data)
    

    iter_submodel_types classmethod

    iter_submodel_types(
        *, recursive: bool = True, include_union_members: bool = True
    ) -> Iterator[tuple[str, type[BaseModel]]]
    

    Iterate through all nested BaseModel types in field annotations.

    Supports field types: - BaseModel (direct type) - list[BaseModel] - dict[str, BaseModel] - BaseModel | OtherModel (unions, when include_union_members=True)

    Parameters:

    Name Type Description Default
    recursive bool

    If True, also iterate through submodel types of submodels

    True
    include_union_members bool

    If True, yield each union member separately

    True

    Yields:

    Type Description
    tuple[str, type[BaseModel]]

    Tuples of (path, model_type) where path is like "field", "field[]", "field{}"

    Source code in src/schemez/schema.py
    @classmethod
    def iter_submodel_types(
        cls, *, recursive: bool = True, include_union_members: bool = True
    ) -> Iterator[tuple[str, type[BaseModel]]]:
        """Iterate through all nested BaseModel types in field annotations.
    
        Supports field types:
        - BaseModel (direct type)
        - list[BaseModel]
        - dict[str, BaseModel]
        - BaseModel | OtherModel (unions, when include_union_members=True)
    
        Args:
            recursive: If True, also iterate through submodel types of submodels
            include_union_members: If True, yield each union member separately
    
        Yields:
            Tuples of (path, model_type) where path is like "field", "field[]", "field{}"
        """
        return _iter_submodel_types(
            cls, recursive=recursive, include_union_members=include_union_members
        )
    

    iter_submodels

    iter_submodels(*, recursive: bool = True) -> Iterator[tuple[str, BaseModel]]
    

    Iterate through all nested BaseModel instances in fields.

    Supports fields of type: - BaseModel (direct instance) - list[BaseModel] - dict[str, BaseModel]

    Parameters:

    Name Type Description Default
    recursive bool

    If True, also iterate through submodels of submodels

    True

    Yields:

    Type Description
    tuple[str, BaseModel]

    Tuples of (path, submodel) where path is like "field", "field[0]", "field['key']"

    Source code in src/schemez/schema.py
    def iter_submodels(self, *, recursive: bool = True) -> Iterator[tuple[str, BaseModel]]:
        """Iterate through all nested BaseModel instances in fields.
    
        Supports fields of type:
        - BaseModel (direct instance)
        - list[BaseModel]
        - dict[str, BaseModel]
    
        Args:
            recursive: If True, also iterate through submodels of submodels
    
        Yields:
            Tuples of (path, submodel) where path is like "field", "field[0]", "field['key']"
        """
        return _iter_submodels(self, recursive=recursive)
    

    merge

    merge(other: Self) -> Self
    

    Merge with another instance by overlaying its non-None values.

    Source code in src/schemez/schema.py
    def merge(self, other: Self) -> Self:
        """Merge with another instance by overlaying its non-None values."""
        from schemez.helpers import merge_models
    
        return merge_models(self, other)
    

    model_dump_markdown

    model_dump_markdown(
        *,
        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: Literal["table", "python_code", "yaml"] = "table",
        exclude_none: bool = True,
        exclude_defaults_yaml: bool = False,
        exclude_unset: bool = False,
        indent: int = 2,
        header_style: Literal["default", "pymdownx"] = "default",
        serialization_mode: Literal["json", "python"] = "json"
    ) -> str
    

    Dump model instance to Markdown documentation.

    Parameters:

    Name Type Description Default
    template str | None

    Custom Jinja2 template string (uses default 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
    include_values bool

    Include current instance values

    True
    display_mode Literal['table', 'python_code', 'yaml']

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

    'table'
    exclude_none bool

    Exclude None values from YAML

    True
    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 Literal['default', 'pymdownx']

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

    'default'
    serialization_mode Literal['json', 'python']

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

    'json'

    Returns:

    Type Description
    str

    Markdown string documenting the model

    Source code in src/schemez/schema.py
    def model_dump_markdown(
        self,
        *,
        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: Literal["table", "python_code", "yaml"] = "table",
        exclude_none: bool = True,
        exclude_defaults_yaml: bool = False,
        exclude_unset: bool = False,
        indent: int = 2,
        header_style: Literal["default", "pymdownx"] = "default",
        serialization_mode: Literal["json", "python"] = "json",
    ) -> str:
        """Dump model instance to Markdown documentation.
    
        Args:
            template: Custom Jinja2 template string (uses default 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
            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"
    
        Returns:
            Markdown string documenting the model
        """
        from schemez.markdown import instance_to_markdown
    
        return instance_to_markdown(
            self,
            template=template,
            header_level=header_level,
            include_defaults=include_defaults,
            include_examples=include_examples,
            include_constraints=include_constraints,
            include_values=include_values,
            display_mode=display_mode,
            exclude_none=exclude_none,
            exclude_defaults_yaml=exclude_defaults_yaml,
            exclude_unset=exclude_unset,
            indent=indent,
            header_style=header_style,
            serialization_mode=serialization_mode,
        )
    

    model_dump_yaml

    model_dump_yaml(
        exclude_none: bool = True,
        exclude_defaults: bool = False,
        exclude_unset: bool = False,
        indent: int = 2,
        default_flow_style: bool | None = None,
        allow_unicode: bool = True,
        comments: bool = False,
        sort_keys: bool = True,
        mode: Literal["json", "python"] = "python",
    ) -> str
    

    Dump configuration to YAML string.

    Parameters:

    Name Type Description Default
    exclude_none bool

    Exclude fields with None values

    True
    exclude_defaults bool

    Exclude fields with default values

    False
    exclude_unset bool

    Exclude fields that are not set

    False
    indent int

    Indentation level for YAML output

    2
    default_flow_style bool | None

    Default flow style for YAML output

    None
    allow_unicode bool

    Allow unicode characters in YAML output

    True
    comments bool

    Include descriptions as comments in the YAML output

    False
    sort_keys bool

    Sort keys in the YAML output

    True
    mode Literal['json', 'python']

    Output mode, either "json" or "python"

    'python'

    Returns:

    Type Description
    str

    YAML string representation of the model

    Source code in src/schemez/schema.py
    def model_dump_yaml(
        self,
        exclude_none: bool = True,
        exclude_defaults: bool = False,
        exclude_unset: bool = False,
        indent: int = 2,
        default_flow_style: bool | None = None,
        allow_unicode: bool = True,
        comments: bool = False,
        sort_keys: bool = True,
        mode: Literal["json", "python"] = "python",
    ) -> str:
        """Dump configuration to YAML string.
    
        Args:
            exclude_none: Exclude fields with None values
            exclude_defaults: Exclude fields with default values
            exclude_unset: Exclude fields that are not set
            indent: Indentation level for YAML output
            default_flow_style: Default flow style for YAML output
            allow_unicode: Allow unicode characters in YAML output
            comments: Include descriptions as comments in the YAML output
            sort_keys: Sort keys in the YAML output
            mode: Output mode, either "json" or "python"
    
        Returns:
            YAML string representation of the model
        """
        import yamling
    
        from schemez.commented_yaml import process_yaml_lines
    
        data = self.model_dump(
            exclude_none=exclude_none,
            exclude_defaults=exclude_defaults,
            exclude_unset=exclude_unset,
            mode=mode,
        )
        base_yaml = yamling.dump_yaml(
            data,
            sort_keys=sort_keys,
            indent=indent,
            default_flow_style=default_flow_style,
            allow_unicode=allow_unicode,
        )
        if not comments:
            return base_yaml
    
        schema = self.model_json_schema()
        yaml_lines = base_yaml.strip().split("\n")
        commented_lines = process_yaml_lines(yaml_lines, schema, as_listitem=False, wrapped_in=None)
    
        return "\n".join(commented_lines)
    

    save

    save(path: JoinablePathLike, overwrite: bool = False) -> None
    

    Save configuration to a YAML file.

    Parameters:

    Name Type Description Default
    path JoinablePathLike

    Path to save the configuration to

    required
    overwrite bool

    Whether to overwrite an existing file

    False

    Raises:

    Type Description
    OSError

    If file cannot be written

    ValueError

    If path is invalid

    Source code in src/schemez/schema.py
    def save(self, path: JoinablePathLike, overwrite: bool = False) -> None:
        """Save configuration to a YAML file.
    
        Args:
            path: Path to save the configuration to
            overwrite: Whether to overwrite an existing file
    
        Raises:
            OSError: If file cannot be written
            ValueError: If path is invalid
        """
        yaml_str = self.model_dump_yaml()
        try:
            file_path = upath.UPath(path)
            if file_path.exists() and not overwrite:
                msg = f"File already exists: {path}"
                raise FileExistsError(msg)  # noqa: TRY301
            file_path.parent.mkdir(parents=True, exist_ok=True)
            file_path.write_text(yaml_str)
        except Exception as exc:
            msg = f"Failed to save configuration to {path}"
            raise ValueError(msg) from exc
    

    to_python_code classmethod

    to_python_code(
        *,
        class_name: str | None = None,
        target_python_version: PythonVersionStr | None = None,
        model_type: str = "pydantic.BaseModel"
    ) -> str
    

    Convert this model to Python code asynchronously.

    Parameters:

    Name Type Description Default
    class_name str | None

    Optional custom class name for the generated code

    None
    target_python_version PythonVersionStr | None

    Target Python version for code generation

    None
    model_type str

    Type of model to generate

    'pydantic.BaseModel'

    Returns:

    Type Description
    str

    Generated Python code as string

    Source code in src/schemez/schema.py
    @classmethod
    def to_python_code(
        cls,
        *,
        class_name: str | None = None,
        target_python_version: PythonVersionStr | None = None,
        model_type: str = "pydantic.BaseModel",
    ) -> str:
        """Convert this model to Python code asynchronously.
    
        Args:
            class_name: Optional custom class name for the generated code
            target_python_version: Target Python version for code generation
            model_type: Type of model to generate
    
        Returns:
            Generated Python code as string
        """
        return model_to_python_code(
            cls,
            class_name=class_name,
            target_python_version=target_python_version,
            model_type=model_type,
        )