CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-types-jsonschema

Type stubs for jsonschema JSON Schema validation library

Overview
Eval results
Files

utilities.mddocs/

Utilities and Type Checking

Utility classes, helper functions, and type validation system for JSON Schema processing. This module provides type checking capabilities, internal utilities, CLI interface, and reflection helpers.

Capabilities

Type Checking System

Flexible type validation system for JSON Schema type keyword validation with customizable type checkers.

class TypeChecker:
    """Registry for type checking functions."""
    
    def __init__(self, type_checkers: dict[str, Callable] | None = None) -> None:
        """
        Initialize type checker.
        
        Args:
            type_checkers: Dictionary mapping type names to check functions
        """
    
    def is_type(self, instance: Any, type: str) -> bool:
        """
        Check if instance is of the specified type.
        
        Args:
            instance: Value to check
            type: Type name to check against
            
        Returns:
            True if instance matches type, False otherwise
        """
    
    def redefine(self, type: str, fn: Callable[[Any, Any], bool]) -> TypeChecker:
        """
        Create new TypeChecker with redefined type check.
        
        Args:
            type: Type name to redefine
            fn: New type checking function
            
        Returns:
            New TypeChecker instance
        """
    
    def redefine_many(self, definitions: dict[str, Callable] | None = None) -> TypeChecker:
        """
        Create new TypeChecker with multiple redefined type checks.
        
        Args:
            definitions: Dictionary of type definitions
            
        Returns:
            New TypeChecker instance
        """
    
    def remove(self, *types: str) -> TypeChecker:
        """
        Create new TypeChecker with specified types removed.
        
        Args:
            *types: Type names to remove
            
        Returns:
            New TypeChecker instance
        """
    
    def __lt__(self, other: TypeChecker) -> bool:
        """Less than comparison for TypeChecker instances."""
    
    def __le__(self, other: TypeChecker) -> bool:
        """Less than or equal comparison for TypeChecker instances."""
    
    def __gt__(self, other: TypeChecker) -> bool:
        """Greater than comparison for TypeChecker instances."""
    
    def __ge__(self, other: TypeChecker) -> bool:
        """Greater than or equal comparison for TypeChecker instances."""

Usage example:

from jsonschema import TypeChecker, Draft7Validator

# Create custom type checker
def is_positive_number(checker, instance):
    return isinstance(instance, (int, float)) and instance > 0

custom_types = TypeChecker()
custom_types = custom_types.redefine('positive-number', is_positive_number)

# Use with validator (requires custom validator creation)
# This is typically done through the create() function

Pre-configured Type Checkers

Ready-to-use type checkers for different JSON Schema draft versions.

# Draft-specific type checkers with appropriate type definitions
draft3_type_checker: TypeChecker
draft4_type_checker: TypeChecker
draft6_type_checker: TypeChecker
draft7_type_checker: TypeChecker

Built-in Type Checking Functions

Standard type checking functions used by JSON Schema validators.

def is_array(checker: TypeChecker, instance: Any) -> bool:
    """Check if instance is an array (list)."""

def is_bool(checker: TypeChecker, instance: Any) -> bool:
    """Check if instance is a boolean."""

def is_integer(checker: TypeChecker, instance: Any) -> bool:
    """Check if instance is an integer."""

def is_null(checker: TypeChecker, instance: Any) -> bool:
    """Check if instance is null (None)."""

def is_number(checker: TypeChecker, instance: Any) -> bool:
    """Check if instance is a number (int or float)."""

def is_object(checker: TypeChecker, instance: Any) -> bool:
    """Check if instance is an object (dict)."""

def is_string(checker: TypeChecker, instance: Any) -> bool:
    """Check if instance is a string."""

def is_any(checker: TypeChecker, instance: Any) -> bool:
    """Always returns True (matches any type)."""

URI Dictionary

URI-aware dictionary for storing schemas with proper URI normalization.

class URIDict(MutableMapping[Any, Any]):
    """Dictionary that normalizes URI keys."""
    
    store: dict
    
    def __init__(self, *args, **kwargs) -> None:
        """Initialize URI dictionary."""
    
    def normalize(self, uri: str) -> str:
        """
        Normalize URI for consistent storage.
        
        Args:
            uri: URI to normalize
            
        Returns:
            Normalized URI string
        """
    
    def __getitem__(self, uri: str) -> Any:
        """Get item by URI key."""
    
    def __setitem__(self, uri: str, value: Any) -> None:
        """Set item by URI key."""
    
    def __delitem__(self, uri: str) -> None:
        """Delete item by URI key."""
    
    def __iter__(self) -> Iterator[str]:
        """Iterate over URI keys."""
    
    def __len__(self) -> int:
        """Get number of stored items."""

Usage example:

from jsonschema._utils import URIDict

# URI dictionary automatically normalizes keys
uri_store = URIDict()
uri_store['http://example.com/schema'] = {"type": "string"}
uri_store['http://example.com/schema/'] = {"type": "number"}  # Different URI

print(len(uri_store))  # May be 1 or 2 depending on normalization

Sentinel Values and Utilities

Utility classes and functions for internal JSON Schema processing.

class Unset:
    """Sentinel class for unset values."""

def load_schema(name: str) -> dict:
    """
    Load a built-in schema by name.
    
    Args:
        name: Schema name to load
        
    Returns:
        Schema dictionary
    """

def indent(string: str, times: int = 1) -> str:
    """
    Indent string by specified number of levels.
    
    Args:
        string: String to indent
        times: Number of indentation levels
        
    Returns:
        Indented string
    """

def format_as_index(indices: Sequence[str | int]) -> str:
    """
    Format indices as readable path string.
    
    Args:
        indices: Sequence of path indices
        
    Returns:
        Formatted path string
    """

def find_additional_properties(instance: dict, schema: dict) -> None:
    """
    Find additional properties not defined in schema.
    
    Args:
        instance: Instance to check
        schema: Schema with property definitions
        
    Returns:
        None (modifies state internally)
    """

def extras_msg(extras: Iterable[str]) -> str:
    """
    Create message for extra properties.
    
    Args:
        extras: Extra property names
        
    Returns:
        Formatted message string
    """

def types_msg(instance: Any, types: Iterable[str]) -> str:
    """
    Create message for type mismatch.
    
    Args:
        instance: Instance that failed type check
        types: Expected types
        
    Returns:
        Formatted message string
    """

def flatten(suitable_for_isinstance: Iterable[type]) -> tuple[type, ...]:
    """
    Flatten types suitable for isinstance check.
    
    Args:
        suitable_for_isinstance: Types to flatten
        
    Returns:
        Flattened type tuple
    """

def ensure_list(thing: Any) -> list:
    """
    Ensure value is a list.
    
    Args:
        thing: Value to convert
        
    Returns:
        List containing the value or the value itself if already a list
    """

def equal(one: Any, two: Any) -> bool:
    """
    Test equality with JSON Schema semantics.
    
    Args:
        one: First value
        two: Second value
        
    Returns:
        True if values are equal according to JSON Schema rules
    """

def unbool(element: Any, true: Any = True, false: Any = False) -> Any:
    """
    Convert boolean to other values.
    
    Args:
        element: Value to convert
        true: Value to return for True
        false: Value to return for False
        
    Returns:
        Converted value
    """

def uniq(container: Iterable[Any]) -> list[Any]:
    """
    Remove duplicates from iterable while preserving order.
    
    Args:
        container: Iterable to deduplicate
        
    Returns:
        List with duplicates removed
    """

Command Line Interface

CLI functions for command-line JSON Schema validation.

def parse_args(args: list[str]) -> argparse.Namespace:
    """
    Parse command line arguments.
    
    Args:
        args: Command line arguments
        
    Returns:
        Parsed arguments namespace
    """

def main(args: list[str] | None = None) -> None:
    """
    Main CLI entry point.
    
    Args:
        args: Command line arguments (sys.argv if None)
    """

def run(
    arguments: argparse.Namespace,
    stdout: IO[str] = sys.stdout,
    stderr: IO[str] = sys.stderr
) -> int:
    """
    Run validation with parsed arguments.
    
    Args:
        arguments: Parsed command line arguments
        stdout: Output stream
        stderr: Error stream
        
    Returns:
        Exit code (0 for success)
    """

# CLI argument parser
parser: argparse.ArgumentParser

Usage example:

import sys
from jsonschema.cli import main

# Run CLI validation
sys.argv = ['jsonschema', '-i', 'data.json', 'schema.json'] 
main()  # Validates data.json against schema.json

Reflection Utilities

Helper functions for dynamic importing and name resolution.

class InvalidName(ValueError):
    """Exception for invalid names."""

class ModuleNotFound(InvalidName):
    """Exception when module cannot be found."""

class ObjectNotFound(InvalidName):  
    """Exception when object cannot be found in module."""

def namedAny(name: str) -> Any:
    """
    Import and return object by fully qualified name.
    
    Args:
        name: Fully qualified name (e.g., 'module.submodule.object')
        
    Returns:
        Imported object
        
    Raises:
        ModuleNotFound: If module cannot be imported
        ObjectNotFound: If object cannot be found in module
        InvalidName: If name format is invalid
    """

def reraise(exception: Exception, traceback: Any) -> None:
    """
    Re-raise exception with traceback.
    
    Args:
        exception: Exception to re-raise
        traceback: Exception traceback
    """

Usage example:

from jsonschema._reflect import namedAny

# Dynamically import function
validate_func = namedAny('jsonschema.validate')
# Now validate_func is the same as: from jsonschema import validate

# Import class
validator_class = namedAny('jsonschema.Draft7Validator')

Usage Examples

Custom Type Checker

from jsonschema import TypeChecker, create, ValidationError

# Define custom type checking functions
def is_positive_int(checker, instance):
    return isinstance(instance, int) and instance > 0

def is_email_like(checker, instance):
    return isinstance(instance, str) and '@' in instance

# Create custom type checker
custom_types = TypeChecker({
    'positive-int': is_positive_int,
    'email-like': is_email_like
})

# Create custom validator with new types
meta_schema = {
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object"
}

CustomValidator = create(
    meta_schema=meta_schema,
    type_checker=custom_types
)

# Use custom validator
schema = {
    "type": "object",
    "properties": {
        "user_id": {"type": "positive-int"},
        "contact": {"type": "email-like"}
    }
}

validator = CustomValidator(schema)

# Valid data
validator.validate({"user_id": 123, "contact": "user@domain.com"})

# Invalid data
try:
    validator.validate({"user_id": -1, "contact": "not-email"})
except ValidationError as e:
    print(f"Validation failed: {e.message}")

URI-based Schema Storage

from jsonschema._utils import URIDict
from jsonschema import RefResolver, Draft7Validator

# Create URI-aware schema store
schema_store = URIDict()
schema_store['http://example.com/user.json'] = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer", "minimum": 0}
    }
}

schema_store['http://example.com/address.json'] = {
    "type": "object", 
    "properties": {
        "street": {"type": "string"},
        "city": {"type": "string"},
        "zipcode": {"type": "string", "pattern": r"^\d{5}$"}
    }
}

# Main schema with references
main_schema = {
    "type": "object",
    "properties": {
        "user": {"$ref": "http://example.com/user.json"},
        "address": {"$ref": "http://example.com/address.json"}
    }
}

# Create resolver with schema store
resolver = RefResolver(
    base_uri="http://example.com/",
    referrer=main_schema,
    store=schema_store
)

validator = Draft7Validator(main_schema, resolver=resolver)

# Validate data with resolved references
data = {
    "user": {"name": "Alice", "age": 30},
    "address": {"street": "123 Main St", "city": "Anytown", "zipcode": "12345"}
}

validator.validate(data)  # References are resolved automatically

Validation Function Helpers

from jsonschema._validators import (
    type as type_validator,
    minimum, maximum,
    required
)

# These are the internal validation functions used by validators
# They follow the signature: validator_func(validator, value, instance, schema)

# Example of how validation functions work internally
class SimpleValidator:
    def __init__(self, schema):
        self.schema = schema
    
    def validate_type(self, instance):
        if "type" in self.schema:
            # This simulates how type validation works internally
            expected_type = self.schema["type"] 
            if expected_type == "string" and not isinstance(instance, str):
                raise ValueError(f"Expected string, got {type(instance).__name__}")
            elif expected_type == "integer" and not isinstance(instance, int):
                raise ValueError(f"Expected integer, got {type(instance).__name__}")
    
    def validate(self, instance):
        self.validate_type(instance)
        # Other validations would follow...

# Usage
validator = SimpleValidator({"type": "string"})
validator.validate("hello")  # Valid
# validator.validate(123)  # Would raise ValueError

Types

from typing import Any, Callable, IO, Iterable, Iterator, MutableMapping, Sequence
import argparse
import sys

# For type checking functions
from jsonschema._types import (
    is_array, is_bool, is_integer, is_null, is_number, 
    is_object, is_string, is_any,
    draft3_type_checker, draft4_type_checker, 
    draft6_type_checker, draft7_type_checker,
    TypeChecker
)

# For CLI functions
from jsonschema.cli import main, parse_args

# For utility classes and functions
from jsonschema._utils import (
    URIDict, find_additional_properties, 
    extras_msg, types_msg, unbool
)

# For reflection utilities
from jsonschema._reflect import namedAny

Install with Tessl CLI

npx tessl i tessl/pypi-types-jsonschema

docs

exceptions.md

format-checker.md

index.md

utilities.md

validators.md

tile.json