CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-marshmallow

A lightweight library for converting complex datatypes to and from native Python datatypes

Pending
Overview
Eval results
Files

schema-definition.mddocs/

Schema Definition

Schema classes define the structure and rules for serializing Python objects to JSON-compatible data and deserializing input data back to Python objects. Schemas provide comprehensive control over field mapping, validation, data transformation, and error handling.

Capabilities

Schema Class

The base Schema class provides core serialization and deserialization functionality with extensive configuration options.

class Schema:
    def __init__(self, *, only=None, exclude=(), many=None, load_only=(), 
                 dump_only=(), partial=None, unknown=None):
        """
        Initialize a Schema instance.

        Parameters:
        - only: list/tuple, fields to include (whitelist)
        - exclude: list/tuple, fields to exclude (blacklist, default: ())
        - many: bool, whether to serialize/deserialize a collection of objects
        - load_only: list/tuple, fields only used during deserialization (default: ())
        - dump_only: list/tuple, fields only used during serialization (default: ())
        - partial: bool/list, allow partial loading (skip required validation)
        - unknown: str, how to handle unknown fields (EXCLUDE/INCLUDE/RAISE)
        """

    def dump(self, obj, *, many=None):
        """
        Serialize objects to JSON-compatible Python data types.

        Parameters:
        - obj: object or list of objects to serialize
        - many: bool, override instance's many setting

        Returns:
        dict or list of dicts with serialized data
        """

    def dumps(self, obj, *, many=None, **kwargs):
        """
        Serialize objects to JSON string.

        Parameters:
        - obj: object or list of objects to serialize
        - many: bool, override instance's many setting
        - **kwargs: additional arguments passed to json.dumps

        Returns:
        str: JSON string representation
        """

    def load(self, json_data, *, many=None, partial=None, unknown=None):
        """
        Deserialize input data to Python objects.

        Parameters:
        - json_data: dict or list of dicts to deserialize
        - many: bool, override instance's many setting
        - partial: bool/list, allow partial loading
        - unknown: str, how to handle unknown fields

        Returns:
        dict or list of dicts with deserialized data

        Raises:
        ValidationError: if validation fails
        """

    def loads(self, json_str, *, many=None, partial=None, unknown=None, **kwargs):
        """
        Deserialize JSON string to Python objects.

        Parameters:
        - json_str: str, JSON string to deserialize
        - many: bool, override instance's many setting
        - partial: bool/list, allow partial loading
        - unknown: str, how to handle unknown fields
        - **kwargs: additional arguments passed to json.loads

        Returns:
        dict or list of dicts with deserialized data

        Raises:
        ValidationError: if validation fails
        """

    def validate(self, json_data, *, many=None, partial=None, unknown=None):
        """
        Validate input data without deserializing.

        Parameters:
        - json_data: dict or list of dicts to validate
        - many: bool, override instance's many setting
        - partial: bool/list, allow partial validation
        - unknown: str, how to handle unknown fields

        Returns:
        dict: validation errors (empty dict if valid)
        """

    class Meta:
        """
        Schema configuration class.
        
        Attributes:
        - fields: tuple, field names to include
        - exclude: tuple, field names to exclude
        - load_only: tuple, fields only used during deserialization
        - dump_only: tuple, fields only used during serialization
        - unknown: str, how to handle unknown fields (EXCLUDE/INCLUDE/RAISE)
        - include: dict, additional fields to include
        - dateformat: str, default date format
        - datetimeformat: str, default datetime format
        - timeformat: str, default time format
        - render_module: module, JSON serialization module (default: json)
        - ordered: bool, whether to preserve field order
        - register: bool, whether to register schema in class registry
        """

Schema Configuration Options

The SchemaOpts class handles schema configuration and Meta class processing.

class SchemaOpts:
    def __init__(self, meta, ordered=False):
        """
        Initialize schema options from Meta class.

        Parameters:
        - meta: Meta class with configuration attributes
        - ordered: bool, whether to preserve field order
        """

Schema Metaclass

The SchemaMeta metaclass processes Schema class definitions and manages field declaration.

class SchemaMeta(type):
    def __new__(cls, name, bases, namespace, **kwargs):
        """
        Create a new Schema class with processed field definitions.
        """

    @classmethod
    def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_fields):
        """
        Get all declared fields for a schema class.

        Parameters:
        - klass: Schema class being created
        - cls_fields: fields declared directly on the class
        - inherited_fields: fields inherited from parent classes
        - dict_fields: fields from Meta.fields

        Returns:
        dict: mapping of field names to Field instances
        """

Usage Examples

Basic Schema Definition

from marshmallow import Schema, fields

class UserSchema(Schema):
    id = fields.Int()
    username = fields.Str(required=True)
    email = fields.Email(required=True)
    created_at = fields.DateTime(dump_only=True)
    password = fields.Str(load_only=True)

# Usage
schema = UserSchema()
user_data = {"id": 1, "username": "john", "email": "john@example.com"}
result = schema.dump(user_data)

Schema with Meta Configuration

class ProductSchema(Schema):
    name = fields.Str()
    price = fields.Decimal()
    description = fields.Str()
    internal_id = fields.Int()
    
    class Meta:
        # Only include specific fields
        fields = ("name", "price", "description")
        # Set default datetime format
        datetimeformat = "%Y-%m-%d %H:%M:%S"
        # Handle unknown fields by including them
        unknown = INCLUDE

Dynamic Schema Creation

# Create schema with runtime field selection
schema = UserSchema(only=("username", "email"))
result = schema.dump(user)

# Exclude sensitive fields
schema = UserSchema(exclude=("password", "internal_id"))
result = schema.dump(user)

# Handle collections
users_data = [user1, user2, user3]
schema = UserSchema(many=True)
result = schema.dump(users_data)

Partial Loading

# Allow partial updates (skip required field validation)
schema = UserSchema()
partial_data = {"username": "new_username"}
result = schema.load(partial_data, partial=True)

# Partial loading for specific fields only
result = schema.load(partial_data, partial=("username", "email"))

Install with Tessl CLI

npx tessl i tessl/pypi-marshmallow

docs

decorators-hooks.md

exceptions-utils.md

field-types.md

index.md

schema-definition.md

validation.md

tile.json