Python lib/cli for JSON/YAML schema validation
—
The Core class provides the main validation functionality for PyKwalify, supporting both file-based and data-based validation with comprehensive error reporting and flexible configuration options.
Creates a Core validation instance with support for various input sources and configuration options.
class Core:
def __init__(
self,
source_file=None,
schema_files=None,
source_data=None,
schema_data=None,
extensions=None,
strict_rule_validation=False,
fix_ruby_style_regex=False,
allow_assertions=False,
file_encoding=None,
schema_file_obj=None,
data_file_obj=None
):
"""
Initialize Core validation instance.
Args:
source_file (str, optional): Path to data file to validate
schema_files (list, optional): List of paths to schema definition files
source_data (dict/list, optional): Data structure to validate
schema_data (dict, optional): Schema definition as data structure
extensions (list, optional): List of paths to Python extension files
strict_rule_validation (bool): Enable strict validation of all rule keywords
fix_ruby_style_regex (bool): Fix Ruby-style regex compatibility issues
allow_assertions (bool): Enable assertion keyword (disabled by default for security)
file_encoding (str, optional): Encoding for reading files
schema_file_obj (file-like, optional): Schema file object
data_file_obj (file-like, optional): Data file object
"""Performs the actual validation process with configurable error handling.
def validate(self, raise_exception=True):
"""
Validate the loaded data against the schema.
Args:
raise_exception (bool): If True, raises SchemaError on validation failure.
If False, logs errors but does not raise exception.
Returns:
object: The validated source data if validation succeeds
Raises:
SchemaError: When validation fails and raise_exception=True
CoreError: When there are configuration or processing errors
"""class Core:
source: dict # Loaded source data
schema: dict # Loaded schema definition
validation_errors: list # List of validation errors
validation_errors_exceptions: list # List of validation error exceptions
root_rule: Rule # Root schema rule object
extensions: list # List of loaded extensions
errors: list # General error list
strict_rule_validation: bool # Strict validation flag
fix_ruby_style_regex: bool # Ruby regex compatibility flag
allow_assertions: bool # Assertion enablement flagfrom pykwalify.core import Core
from pykwalify.errors import SchemaError, CoreError
try:
# Single schema file
c = Core(source_file="data.yaml", schema_files=["schema.yaml"])
c.validate(raise_exception=True)
print("Validation successful!")
# Multiple schema files
c = Core(
source_file="complex_data.yaml",
schema_files=["base_schema.yaml", "extended_schema.yaml"]
)
c.validate(raise_exception=True)
except SchemaError as e:
print(f"Schema validation failed: {e}")
print(f"Error path: {e.path}")
except CoreError as e:
print(f"Core processing error: {e}")from pykwalify.core import Core
# Simple data validation
data = {
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}
schema = {
"type": "map",
"mapping": {
"name": {"type": "str", "required": True},
"age": {"type": "int", "range": {"min": 0, "max": 120}},
"email": {"type": "email"}
}
}
c = Core(source_data=data, schema_data=schema)
validated_data = c.validate(raise_exception=False)
if c.validation_errors:
print("Validation errors:")
for error in c.validation_errors:
print(f"- {error}")
else:
print(f"Validation successful! Data: {validated_data}")from pykwalify.core import Core
# With extensions and custom configuration
c = Core(
source_file="data.yaml",
schema_files=["schema.yaml"],
extensions=["custom_validators.py"],
strict_rule_validation=True,
allow_assertions=True,
file_encoding="utf-8"
)
# Access validation details
c.validate(raise_exception=True)
print(f"Root rule type: {c.root_rule.type}")
print(f"Loaded extensions: {c.extensions}")from pykwalify.core import Core
from io import StringIO
# Using file-like objects
schema_content = """
type: map
mapping:
name: {type: str}
count: {type: int}
"""
data_content = """
name: "Test Item"
count: 42
"""
schema_obj = StringIO(schema_content)
data_obj = StringIO(data_content)
c = Core(schema_file_obj=schema_obj, data_file_obj=data_obj)
c.validate(raise_exception=True)from pykwalify.core import Core
from pykwalify.errors import (
SchemaError, CoreError, RuleError,
NotMappingError, NotSequenceError, SchemaConflict
)
try:
c = Core(source_file="data.yaml", schema_files=["schema.yaml"])
c.validate(raise_exception=True)
except SchemaError as e:
print(f"Schema validation failed: {e.msg}")
print(f"Error location: {e.path}")
print(f"Error code: {e.retcode}")
except CoreError as e:
print(f"Core processing error: {e.msg}")
except NotMappingError as e:
print(f"Expected mapping but got different type: {e.msg}")
except NotSequenceError as e:
print(f"Expected sequence but got different type: {e.msg}")
except RuleError as e:
print(f"Rule processing error: {e.msg}")
except SchemaConflict as e:
print(f"Schema conflict detected: {e.msg}")from pykwalify.core import Core
c = Core(source_data=data, schema_data=schema)
is_valid = c.validate(raise_exception=False)
if not is_valid:
print("Validation failed with errors:")
# Access detailed error information
if c.validation_errors:
for error in c.validation_errors:
print(f"- {error}")
# Access error exceptions for detailed information
if c.validation_errors_exceptions:
for exc in c.validation_errors_exceptions:
print(f"- Exception: {exc.msg} at {exc.path}")Install with Tessl CLI
npx tessl i tessl/pypi-pykwalify