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
- The
parsemethod receives an arbitrary value that may or may not be a field metadata. - Checks whether the value is a dictionary containing the key
"type", identifying it as valid metadata for analysis. - If it is metadata, it delegates to the private method
_parse_metadata, which does the detailed transformation. _parse_metadataextracts the given type and checks whether the field is required (required).- 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. - Maps the string type to the corresponding Python type, using the
_map_typemethod. - If the field is not required, the type is wrapped in
Optionalto support the absence of a value. - Creates a Pydantic
Fieldwith parameters such as default value, description, examples and size constraints. - Returns a tuple made up of the final type and the
Fieldobject for direct use in Pydantic models. - If the value is not a recognized metadata, it returns
None. - If there is a parsing error, it raises a
RuntimeErrorexception with details.
#Class Methods Table
| Method | Description |
|---|---|
__init__ | Not explicitly implemented (default constructor) |
parse | Analyzes the value and returns the type and Field for metadata, or None |
_parse_metadata | Converts a metadata dictionary into a Pydantic type and a configured Field |
_map_type | Maps 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_metadataand_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_typemethod 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, orNoneif 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 theFieldinformation.
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) orAnyif 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_shemaSource: src/content_parse/pydantic_schema.py