Yamale
Yamale (ya·ma·lē) is a schema and validator for YAML. It allows for defining schemas in YAML files and validating other YAML data against them, supporting a wide range of data types and custom validators. The current version is 6.1.0, and it generally follows a regular release cadence with several minor and major releases each year.
Warnings
- breaking In version 6.0.0, the command-line interface (CLI) was updated to strictly enforce that all paths provided to CLI arguments must exist. Previously, non-existent paths might have been silently ignored or handled differently.
- breaking Version 5.0.0 dropped support for Python versions older than 3.8. Running Yamale on Python 3.7 or earlier will result in errors.
- gotcha Yamale schemas should always originate from trusted sources. The library does not inherently protect against intentionally malicious schemas, which could potentially lead to arbitrary code execution if an attacker controls the schema file. (A specific code injection vulnerability, CVE-2021-38305, was addressed in v3.0.8).
- gotcha By default, Yamale operates in 'strict' mode. This means that if the data being validated contains elements (keys in a map, or items in a list) that are not explicitly defined in the schema, validation will fail. This can be unexpected if you want to allow extra data.
Install
-
pip install yamale -
pip install yamale[ruamel]
Imports
- yamale
import yamale
- make_schema
yamale.make_schema('./schema.yaml') - make_data
yamale.make_data('./data.yaml') - validate
yamale.validate(schema, data)
Quickstart
import yamale
import os
# Create dummy schema.yaml and data.yaml files for demonstration
# In a real scenario, these would be pre-existing files.
with open('schema.yaml', 'w') as f:
f.write('name: str()\nage: int(max=200)\nawesome: bool()')
with open('data.yaml', 'w') as f:
f.write('name: Bill\nage: 26\nawesome: True')
try:
# Import Yamale and make a schema object:
schema = yamale.make_schema('./schema.yaml')
# Create a Data object
data = yamale.make_data('./data.yaml')
# Validate data against the schema. Throws a ValueError if data is invalid.
yamale.validate(schema, data)
print('Validation success! Data is valid against the schema.')
except ValueError as e:
print(f'Validation failed!\n{e}')
except FileNotFoundError as e:
print(f'Error: {e}. Ensure schema.yaml and data.yaml exist.')
finally:
# Clean up dummy files
if os.path.exists('schema.yaml'):
os.remove('schema.yaml')
if os.path.exists('data.yaml'):
os.remove('data.yaml')