Content Parse

Field Metadata Parser

The FieldMetadataParser class is responsible for interpreting metadata defined in dictionaries for data fields and converting it into types and fields compatible with the Pydantic library.

On this page

    #Overview

    The FieldMetadataParser class is responsible for interpreting metadata defined in dictionaries for data fields and converting it into types and fields compatible with the Pydantic library. It analyzes information such as the field type, whether it is required, description, examples and constraints, thus generating a representation ready for validation and use in Pydantic models.

    This process is fundamental for systems that receive dynamic data schemas or external configuration and need to build validation models in an automated and consistent way. With this class, it is possible to turn a JSON-like specification directly into Pydantic types, ensuring automatic validation and documentation generated from the metadata.

    In practice, it can be used in data frameworks, dynamic schema imports, or any application that models data from flexible definitions.

    #Execution Flow

    1. The parse method receives an arbitrary value that may or may not be a field metadata.
    2. Checks whether the value is a dictionary containing the key "type", identifying it as valid metadata for analysis.
    3. If it is metadata, it delegates to the private method _parse_metadata, which does the detailed transformation.
    4. _parse_metadata extracts the given type and checks whether the field is required (required).
    5. If the type is "list", it looks up the definition of the item type (items), and may generate a generic type or a nested model for complex objects.
    6. Maps the string type to the corresponding Python type, using the _map_type method.
    7. If the field is not required, the type is wrapped in Optional to support the absence of a value.
    8. Creates a Pydantic Field with parameters such as default value, description, examples and size constraints.
    9. Returns a tuple made up of the final type and the Field object for direct use in Pydantic models.
    10. If the value is not a recognized metadata, it returns None.
    11. If there is a parsing error, it raises a RuntimeError exception with details.

    #Class Methods Table

    MethodDescription
    __init__Not explicitly implemented (default constructor)
    parseAnalyzes the value and returns the type and Field for metadata, or None
    _parse_metadataConverts a metadata dictionary into a Pydantic type and a configured Field
    _map_typeMaps a string type name to the corresponding Python type

    #Environment Variables

    No environment variable is needed for this class to work.

    #Key Architecture Points and Insights

    • The class uses encapsulation, restricting helper functions to the private scope (_parse_metadata and _map_type).
    • It uses dynamic creation of Pydantic models (create_model) to represent nested complex types (objects inside lists), allowing flexibility and extensibility.
    • The parser interprets a JSON-like structure to produce annotated types and complete information for validation — making integration with dynamic data easier.
    • It supports optional attributes, default values, descriptions and examples, promoting automatic documentation via Pydantic.
    • Explicit error handling with clear messages makes debugging easier.
    • The _map_type method is easily extensible to new types, just by adding them to the dictionary.

    #Class and Methods Description

    #FieldMetadataParser Class

    #Description

    Class to analyze metadata provided in dictionaries and turn it into types and fields configured for use with Pydantic. It makes it easier to dynamically create validation models from external specifications, interpreting types, whether fields are required and descriptive metadata.

    #Constructor Arguments

    No parameters in the constructor.

    #Methods

    #1. parse

    Description

    Receives any value and, if it is a dictionary that defines field metadata (with the key "type"), returns a tuple containing the resulting Pydantic type and a Field object configured with the properties. Otherwise, it returns None.

    Arguments

    • value (Any): Value to be analyzed as field metadata.

    Returns

    • Tuple[Any, Any] | None: Tuple with the field type and the Field object, or None if it is not metadata.

    Raises

    • RuntimeError: If any error occurs while analyzing the metadata, an exception with an explanatory message is raised.

    Examples

    # Metadado válido para um campo inteiro obrigatório
    result = parser.parse({"type": "int", "required": True, "description": "Idade do usuário"})
    # result será algo como (int, Field(..., description="Idade do usuário"))
    
    # Metadado inválido ou não seguindo o padrão retorna None
    result = parser.parse("apenas uma string")
    # result será None

    #2. _parse_metadata

    Description

    Private helper method that receives a validated metadata dictionary, extracts its type, setting up the type and the properties of the field, especially handling lists and nested objects, returning the tuple with the Pydantic type and the Field object.

    Arguments

    • value (Dict[str, Any]): Dictionary containing the field's properties, such as type, requirement, examples, among others.

    Returns

    • Tuple[Any, Any]: Tuple with the field type and the Field information.

    Raises

    • ValueError: If the type is "list" and does not contain the mandatory definition of the key "items".

    Examples

    # Parse de um campo do tipo lista de inteiros não obrigatória
    type_, field = parser._parse_metadata({
        "type": "list",
        "items": {"type": "int"},
        "required": False,
        "description": "Lista de números"
    })
    # type_ será Optional[List[int]]
    # field conterá description e configurações
    
    # Parse de um campo objeto aninhado dentro da lista
    type_, field = parser._parse_metadata({
        "type": "list",
        "items": {
            "type": "object",
            "properties": {
                "nome": {"type": "str", "description": "Nome do item"}
            }
        }
    })
    # type_ será List[ModeloDinâmico]
    # field configurado conforme descrito

    #3. _map_type

    Description

    Maps a type name represented by a string to the corresponding Python type, used in Pydantic modeling. If the type is not recognized, it returns Any as a fallback.

    Arguments

    • type_name (str): String representing the type, for example "str", "int", "list".

    Returns

    • tipo: Corresponding Python type (e.g. str, int, list) or Any if not recognized.

    Examples

    if __name__ == "__main__":
        parser = FieldMetadataParser()
    
        test_cases = [
            {
                "input": {
                    "type": "str",
                    "description": "Nome do personagem",
                    "example": "John"
                }
            },
            {
                "input": {
                    "type": "int",
                    "default": 10
                }
            },
            {
                "input": "valor simples"
            }
        ]
    
        for i, case in enumerate(test_cases, 1):
            result = parser.parse(case["input"])
            print(f"\nTeste {i}")
            print("Input:", case["input"])
            print("Output:", result)
    
    # python -m src.content_parse.pydantic_shema

    Source: src/content_parse/pydantic_schema.py

    Esc
    ↑↓navigate Enteropen