Python lib/cli for JSON/YAML schema validation
—
The Rule class provides schema rule definition and management, serving as the building blocks for creating complex validation schemas with type constraints, length validation, pattern matching, and custom validation functions.
Creates a Rule instance representing a schema validation rule.
class Rule:
def __init__(self, schema=None, parent=None, strict_rule_validation=False):
"""
Initialize a Rule instance.
Args:
schema (dict, optional): Schema definition dictionary
parent (Rule, optional): Parent rule for nested rules
strict_rule_validation (bool): Enable strict validation of rule keywords
"""def init(self, schema, path):
"""
Initialize rule from schema definition.
Args:
schema (dict): Schema definition
path (str): Path context for error reporting
"""
def keywords(self):
"""
Get list of supported keywords for this rule type.
Returns:
list: List of supported keyword strings
"""
def check_type_keywords(self, schema, rule, path):
"""
Check that keywords are valid for the rule type.
Args:
schema (dict): Schema definition
rule (Rule): Rule instance
path (str): Path context
"""
def check_conflicts(self, schema, rule, path):
"""
Check for conflicting rule definitions.
Args:
schema (dict): Schema definition
rule (Rule): Rule instance
path (str): Path context
"""All rule properties support both getting and setting values:
@property
def type(self):
"""The data type this rule validates (str, int, float, map, seq, etc.)"""
@property
def required(self):
"""Whether this field is required (bool)"""
@property
def nullable(self):
"""Whether null/None values are allowed (bool)"""
@property
def default(self):
"""Default value if field is missing"""
@property
def desc(self):
"""Description of this rule (str)"""
@property
def example(self):
"""Example value for this rule"""@property
def range(self):
"""Range constraints for numeric values (dict with min/max keys)"""
@property
def length(self):
"""Length constraints for strings/collections (dict with min/max keys)"""
@property
def pattern(self):
"""Regular expression pattern for string validation (str)"""
@property
def enum(self):
"""List of allowed values (list)"""
@property
def unique(self):
"""Whether sequence values must be unique (bool)"""@property
def sequence(self):
"""Rules for sequence (list) validation (list of Rule objects)"""
@property
def mapping(self):
"""Rules for mapping (dict) validation (dict of Rule objects)"""
@property
def allowempty_map(self):
"""Whether empty mappings are allowed (bool)"""@property
def func(self):
"""Custom validation function name (str)"""
@property
def assertion(self):
"""Assertion expression for custom validation (str)"""
@property
def include_name(self):
"""Name of partial schema to include (str)"""
@property
def matching(self):
"""Matching pattern for flexible validation (str)"""
@property
def matching_rule(self):
"""Rule to apply for matching validation (Rule)"""
@property
def extensions(self):
"""List of extension files (list)"""
@property
def format(self):
"""Format specification for validation (str)"""
@property
def version(self):
"""Schema version specification"""@property
def parent(self):
"""Parent rule for nested rules (Rule)"""
@property
def schema(self):
"""Original schema definition (dict)"""
@property
def schema_str(self):
"""String representation of schema (str)"""
@property
def name(self):
"""Rule name identifier (str)"""
@property
def ident(self):
"""Rule identifier (int)"""
@property
def pattern_regexp(self):
"""Compiled regular expression pattern"""
@property
def type_class(self):
"""Python class for the rule type"""
@property
def map_regex_rule(self):
"""Regex rule for mapping validation"""
@property
def regex_mappings(self):
"""Regex mapping rules (dict)"""from pykwalify.rule import Rule
# Create a simple string rule
schema_def = {
"type": "str",
"required": True,
"desc": "User name"
}
rule = Rule()
rule.init(schema_def, "/name")
print(f"Rule type: {rule.type}")
print(f"Required: {rule.required}")
print(f"Description: {rule.desc}")from pykwalify.rule import Rule
# Numeric range validation
number_schema = {
"type": "int",
"range": {"min": 1, "max": 100},
"desc": "Age in years"
}
age_rule = Rule()
age_rule.init(number_schema, "/age")
# String pattern validation
email_schema = {
"type": "str",
"pattern": r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$",
"desc": "Email address"
}
email_rule = Rule()
email_rule.init(email_schema, "/email")
# Enumeration validation
status_schema = {
"type": "str",
"enum": ["active", "inactive", "pending"],
"default": "pending"
}
status_rule = Rule()
status_rule.init(status_schema, "/status")from pykwalify.rule import Rule
# List of strings with length constraints
tags_schema = {
"type": "seq",
"sequence": [
{
"type": "str",
"length": {"min": 1, "max": 50}
}
],
"length": {"min": 1, "max": 10}
}
tags_rule = Rule()
tags_rule.init(tags_schema, "/tags")
# List with unique values
ids_schema = {
"type": "seq",
"sequence": [{"type": "int"}],
"unique": True
}
ids_rule = Rule()
ids_rule.init(ids_schema, "/ids")from pykwalify.rule import Rule
# Complex nested mapping
user_schema = {
"type": "map",
"mapping": {
"name": {
"type": "str",
"required": True,
"length": {"min": 1, "max": 100}
},
"age": {
"type": "int",
"range": {"min": 0, "max": 120}
},
"email": {
"type": "str",
"format": "email"
},
"addresses": {
"type": "seq",
"sequence": [{
"type": "map",
"mapping": {
"street": {"type": "str", "required": True},
"city": {"type": "str", "required": True},
"zipcode": {"type": "str", "pattern": r"^\d{5}(-\d{4})?$"}
}
}]
}
}
}
user_rule = Rule()
user_rule.init(user_schema, "/user")from pykwalify.rule import Rule
# Using custom validation function
custom_schema = {
"type": "str",
"func": "validate_custom_format",
"desc": "Custom validated field"
}
custom_rule = Rule()
custom_rule.init(custom_schema, "/custom_field")
print(f"Custom function: {custom_rule.func}")from pykwalify.rule import Rule
# Create rule and modify properties
rule = Rule()
rule.type = "str"
rule.required = True
rule.length = {"min": 3, "max": 50}
rule.pattern = r"^[a-zA-Z]+$"
rule.desc = "Alphabetic string"
# Access computed properties
print(f"Type class: {rule.type_class}")
print(f"Keywords: {rule.keywords()}")
# Check if pattern was compiled
if rule.pattern_regexp:
print("Pattern successfully compiled")from pykwalify.rule import Rule
import pykwalify
# Set up partial schema
pykwalify.partial_schemas["address"] = {
"type": "map",
"mapping": {
"street": {"type": "str", "required": True},
"city": {"type": "str", "required": True},
"zipcode": {"type": "str"}
}
}
# Use partial schema in rule
schema_with_include = {
"type": "map",
"mapping": {
"name": {"type": "str"},
"home_address": {"include": "address"},
"work_address": {"include": "address"}
}
}
rule = Rule()
rule.init(schema_with_include, "/person")Supported type values:
str - String valuesint - Integer valuesfloat - Floating point valuesbool - Boolean valuesmap - Dictionary/mapping valuesseq - List/sequence valuesany - Any value typetext - String or numeric valuesnumber - Integer or float valuesscalar - Any non-collection valuetimestamp - Timestamp valuesdate - Date valuesemail - Email format stringsurl - URL format stringsAvailable constraint keywords by type:
required, nullable, default, desc, examplelength, pattern, enum, formatrange, enumlength, unique (sequences only)mapping, allowempty_mapsequence, uniquefunc, assertion, include, matching, extensionsInstall with Tessl CLI
npx tessl i tessl/pypi-pykwalify