Python Data Structures for Humans - a library for data validation and transformation using structured models
—
Essential field types for common data validation and conversion in Schematics. These types handle fundamental data types with comprehensive validation options and automatic type conversion.
Handle text data with length validation, pattern matching, and encoding support.
class StringType(BaseType):
"""
Unicode string field with validation and formatting.
Supports regex patterns, length constraints, and custom validation.
Automatically converts input to Unicode strings.
"""
def __init__(self, regex=None, max_length=None, min_length=None, **kwargs):
"""
Initialize string field.
Args:
regex (str, optional): Regular expression pattern for validation
max_length (int, optional): Maximum string length
min_length (int, optional): Minimum string length
**kwargs: Base field options (required, default, etc.)
"""
class MultilingualStringType(BaseType):
"""
Multi-language string field with localization support.
Stores strings in multiple languages with locale-based retrieval.
"""Handle various numeric types with range validation and precision control.
class IntType(BaseType):
"""
Integer field with range validation.
Converts strings and floats to integers with optional min/max constraints.
"""
def __init__(self, min_value=None, max_value=None, **kwargs):
"""
Initialize integer field.
Args:
min_value (int, optional): Minimum allowed value
max_value (int, optional): Maximum allowed value
**kwargs: Base field options
"""
class LongType(IntType):
"""
Alias for IntType providing Python 2/3 compatibility.
"""
class FloatType(BaseType):
"""
Float field with range validation and precision handling.
"""
def __init__(self, min_value=None, max_value=None, **kwargs):
"""
Initialize float field.
Args:
min_value (float, optional): Minimum allowed value
max_value (float, optional): Maximum allowed value
**kwargs: Base field options
"""
class DecimalType(BaseType):
"""
Fixed-point decimal field using Python's Decimal type.
Provides exact decimal arithmetic for financial calculations.
"""
def __init__(self, min_value=None, max_value=None, **kwargs):
"""
Initialize decimal field.
Args:
min_value (Decimal, optional): Minimum allowed value
max_value (Decimal, optional): Maximum allowed value
**kwargs: Base field options
"""
class NumberType(BaseType):
"""
Generic number field accepting int, float, or Decimal.
Base class for numeric types with common validation logic.
"""Handle boolean data with flexible input conversion.
class BooleanType(BaseType):
"""
Boolean field with string coercion support.
Converts various string representations ('true', 'false', '1', '0')
and numeric values to boolean.
"""
def __init__(self, **kwargs):
"""
Initialize boolean field.
Args:
**kwargs: Base field options
"""Handle UUID data with format validation and conversion.
class UUIDType(BaseType):
"""
UUID field supporting string and UUID object input.
Validates UUID format and converts between string and UUID objects.
"""
def __init__(self, **kwargs):
"""
Initialize UUID field.
Args:
**kwargs: Base field options
"""Handle temporal data with format parsing and timezone support.
class DateType(BaseType):
"""
Date field with ISO8601 string parsing.
Converts date strings to Python date objects with format validation.
"""
def __init__(self, formats=None, **kwargs):
"""
Initialize date field.
Args:
formats (list, optional): Custom date format strings
**kwargs: Base field options
"""
class DateTimeType(BaseType):
"""
DateTime field with timezone and format support.
Handles various datetime formats and timezone conversions.
"""
def __init__(self, formats=None, convert_tz=True, **kwargs):
"""
Initialize datetime field.
Args:
formats (list, optional): Custom datetime format strings
convert_tz (bool): Whether to handle timezone conversion
**kwargs: Base field options
"""
class UTCDateTimeType(DateTimeType):
"""
UTC-normalized datetime field.
Automatically converts all datetime values to UTC timezone.
"""
class TimestampType(BaseType):
"""
Unix timestamp field converting float/int to datetime.
Handles Unix timestamps (seconds since epoch) with datetime conversion.
"""
class TimedeltaType(BaseType):
"""
Time duration field using Python's timedelta.
Supports various duration input formats and timedelta objects.
"""Handle cryptographic hashes with format validation.
class HashType(BaseType):
"""
Base class for hash fields with length and character validation.
Validates hexadecimal hash strings of specified lengths.
"""
class MD5Type(HashType):
"""
MD5 hash field (32 hexadecimal characters).
Validates MD5 hash format and case-insensitive input.
"""
class SHA1Type(HashType):
"""
SHA1 hash field (40 hexadecimal characters).
Validates SHA1 hash format and case-insensitive input.
"""Handle geographic coordinate data.
class GeoPointType(BaseType):
"""
Geographic coordinate field storing [latitude, longitude] pairs.
Validates coordinate ranges and supports various input formats.
"""
def __init__(self, **kwargs):
"""
Initialize geographic point field.
Args:
**kwargs: Base field options
"""All field types inherit from BaseType which provides common functionality.
class BaseType:
"""
Base class for all field types providing common validation and conversion.
Defines the field interface and shared functionality for validation,
conversion, serialization, and mock data generation.
"""
def __init__(self, required=False, default=Undefined, serialized_name=None,
choices=None, validators=None, deserialize_from=None,
export_level=None, serialize_when_none=None,
messages=None, metadata=None):
"""
Initialize base field type.
Args:
required (bool): Whether field is required
default: Default value if not provided (Undefined for no default)
serialized_name (str, optional): Name for serialization
choices (list, optional): Allowed values
validators (list, optional): Additional validator functions
deserialize_from (str/list, optional): Source field names for deserialization
export_level (int, optional): Export level for field inclusion
serialize_when_none (bool, optional): Whether to serialize None values
messages (dict, optional): Custom error messages
metadata (dict, optional): Additional field metadata
"""
def validate(self, value, context=None):
"""
Validate field value according to field rules.
Args:
value: Value to validate
context: Validation context
Raises:
ValidationError: If validation fails
"""
def convert(self, value, context=None):
"""
Convert input value to field's native type.
Args:
value: Value to convert
context: Conversion context
Returns:
Converted value
Raises:
ConversionError: If conversion fails
"""from schematics.models import Model
from schematics.types import StringType
class User(Model):
username = StringType(required=True, min_length=3, max_length=20,
regex=r'^[a-zA-Z0-9_]+$')
email = StringType(required=True)
bio = StringType(max_length=500)
# Valid data
user = User({
'username': 'john_doe',
'email': 'john@example.com',
'bio': 'Software developer'
})
user.validate() # Successfrom schematics.types import IntType, FloatType, DecimalType
from decimal import Decimal
class Product(Model):
quantity = IntType(min_value=0, required=True)
weight = FloatType(min_value=0.0, max_value=1000.0)
price = DecimalType(min_value=Decimal('0.00'), required=True)
product = Product({
'quantity': 10,
'weight': 2.5,
'price': '19.99' # String converted to Decimal
})
product.validate()from schematics.types import DateType, DateTimeType, TimestampType
from datetime import datetime
class Event(Model):
event_date = DateType(required=True)
created_at = DateTimeType(default=datetime.utcnow)
timestamp = TimestampType()
# Various input formats supported
event = Event({
'event_date': '2024-12-25', # ISO date string
'timestamp': 1640995200 # Unix timestamp
})
event.validate()Install with Tessl CLI
npx tessl i tessl/pypi-schematics