CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cattrs

Composable complex class support for attrs and dataclasses with (un)structuring and validation.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

code-generation.mddocs/

Code Generation and Optimization

High-performance code generation utilities for creating specialized structuring and unstructuring functions. The cattrs.gen module provides tools for creating optimized, type-specific converter functions that can significantly improve performance for critical code paths.

Capabilities

Structure Function Generation

Functions for generating optimized structuring functions tailored to specific classes and types.

from cattrs.gen import (
    make_dict_structure_fn,
    make_dict_structure_fn_from_attrs,
    make_mapping_structure_fn
)

def make_dict_structure_fn(cl, converter, **kwargs):
    """
    Generate specialized dict structuring functions for attrs classes/dataclasses.
    
    Creates optimized functions that can structure dictionaries into class instances
    faster than the generic converter methods.
    
    Parameters:
    - cl: The class to generate a structuring function for
    - converter: The converter instance to use for nested structuring
    - **kwargs: Additional generation options
    
    Returns:
    Function that structures dictionaries into instances of the specified class
    """

def make_dict_structure_fn_from_attrs(attrs_and_types, cl, converter, **kwargs):
    """
    Generate dict structuring functions from attribute lists.
    
    Creates structuring functions based on explicit attribute specifications
    rather than introspecting the class.
    
    Parameters:
    - attrs_and_types: List of (attribute, type) tuples
    - cl: Target class for structuring
    - converter: Converter instance for nested types
    - **kwargs: Additional options
    
    Returns:
    Optimized structuring function for the specified attributes
    """

def make_mapping_structure_fn(cl, converter, mapping_key=None, **kwargs):
    """
    Generate structuring functions for mappings.
    
    Creates functions optimized for structuring mapping types (dict-like objects)
    with specific key and value type handling.
    
    Parameters:
    - cl: The mapping class to structure into
    - converter: Converter for key/value structuring
    - mapping_key: Optional key transformation function
    - **kwargs: Additional generation options
    
    Returns:
    Optimized mapping structuring function
    """

Unstructure Function Generation

Functions for generating optimized unstructuring functions for various data types.

from cattrs.gen import (
    make_dict_unstructure_fn,
    make_dict_unstructure_fn_from_attrs,
    make_hetero_tuple_unstructure_fn,
    make_iterable_unstructure_fn,
    make_mapping_unstructure_fn
)

def make_dict_unstructure_fn(cl, converter, **kwargs):
    """
    Generate specialized dict unstructuring functions for attrs classes/dataclasses.
    
    Creates optimized functions that convert class instances to dictionaries
    faster than generic converter methods.
    
    Parameters:
    - cl: The class to generate an unstructuring function for
    - converter: Converter instance for nested unstructuring
    - **kwargs: Additional generation options (unstructure_as, etc.)
    
    Returns:
    Function that unstructures instances into dictionaries
    """

def make_dict_unstructure_fn_from_attrs(attrs_and_types, cl, converter, **kwargs):
    """
    Generate dict unstructuring functions from attribute lists.
    
    Creates unstructuring functions based on explicit attribute specifications.
    
    Parameters:
    - attrs_and_types: List of (attribute, type) tuples to unstructure
    - cl: Source class for unstructuring
    - converter: Converter instance for nested types
    - **kwargs: Additional options
    
    Returns:
    Optimized unstructuring function for the specified attributes
    """

def make_hetero_tuple_unstructure_fn(tuple_type, converter, **kwargs):
    """
    Generate unstructuring functions for heterogeneous tuples.
    
    Creates functions optimized for unstructuring tuples with mixed element types.
    
    Parameters:
    - tuple_type: The tuple type to unstructure (e.g., Tuple[int, str, bool])
    - converter: Converter for element unstructuring
    - **kwargs: Additional options
    
    Returns:
    Optimized heterogeneous tuple unstructuring function
    """

def make_iterable_unstructure_fn(iterable_type, converter, **kwargs):
    """
    Generate unstructuring functions for iterables.
    
    Creates functions optimized for unstructuring lists, sets, and other iterables.
    
    Parameters:
    - iterable_type: The iterable type (e.g., List[MyClass], Set[str])
    - converter: Converter for element unstructuring
    - **kwargs: Additional options
    
    Returns:
    Optimized iterable unstructuring function
    """

def make_mapping_unstructure_fn(mapping_type, converter, **kwargs):
    """
    Generate unstructuring functions for mappings.
    
    Creates functions optimized for unstructuring dictionary-like objects.
    
    Parameters:
    - mapping_type: The mapping type (e.g., Dict[str, MyClass])
    - converter: Converter for key/value unstructuring
    - **kwargs: Additional options
    
    Returns:
    Optimized mapping unstructuring function
    """

Override System

Tools for creating fine-grained customizations of field handling during code generation.

from cattrs.gen import override, AttributeOverride

def override(
    rename=None,
    omit_if_default=None,
    struct_hook=None,
    unstruct_hook=None,
    **kwargs
):
    """
    Create attribute overrides for customizing field handling.
    
    Provides field-level control over structuring and unstructuring behavior
    when generating optimized converter functions.
    
    Parameters:
    - rename: Alternative name for the field in unstructured data
    - omit_if_default: Whether to omit field if it has the default value
    - struct_hook: Custom structuring function for this field
    - unstruct_hook: Custom unstructuring function for this field
    - **kwargs: Additional override options
    
    Returns:
    AttributeOverride instance for use with converter configuration
    """

class AttributeOverride:
    """
    Class for specifying field-level overrides in code generation.
    
    Encapsulates customization options for individual fields when generating
    optimized structuring and unstructuring functions.
    """
    def __init__(
        self,
        rename=None,
        omit_if_default=None,
        struct_hook=None,
        unstruct_hook=None,
        **kwargs
    ):
        """
        Initialize attribute override.
        
        Parameters match those of the override() function.
        """

TypedDict Support

Specialized code generation for TypedDict classes.

from cattrs.gen.typeddicts import make_dict_structure_fn, make_dict_unstructure_fn

def make_dict_structure_fn(cl, converter, **kwargs):
    """
    Generate TypedDict structuring functions.
    
    Creates optimized functions specifically for structuring data into TypedDict
    classes with proper type checking and validation.
    
    Parameters:
    - cl: The TypedDict class to structure into
    - converter: Converter instance for nested structuring
    - **kwargs: Additional options
    
    Returns:
    Optimized TypedDict structuring function
    """

def make_dict_unstructure_fn(cl, converter, **kwargs):
    """
    Generate TypedDict unstructuring functions.
    
    Creates functions optimized for unstructuring TypedDict instances while
    preserving type information and structure.
    
    Parameters:
    - cl: The TypedDict class to unstructure from
    - converter: Converter instance for nested unstructuring
    - **kwargs: Additional options
    
    Returns:
    Optimized TypedDict unstructuring function
    """

Usage Examples

Basic Function Generation

from cattrs import Converter
from cattrs.gen import make_dict_structure_fn, make_dict_unstructure_fn
from attrs import define

@define
class User:
    name: str
    age: int
    email: str

converter = Converter()

# Generate optimized functions for the User class
structure_user = make_dict_structure_fn(User, converter)
unstructure_user = make_dict_unstructure_fn(User, converter)

# Use the generated functions directly for better performance
user_data = {"name": "Alice", "age": 30, "email": "alice@example.com"}
user = structure_user(user_data)  # Faster than converter.structure()

user_dict = unstructure_user(user)  # Faster than converter.unstructure()

Using Overrides for Customization

from cattrs import Converter
from cattrs.gen import make_dict_structure_fn, make_dict_unstructure_fn, override
from attrs import define
from datetime import datetime

@define
class Event:
    name: str
    timestamp: datetime
    description: str = "No description"

converter = Converter()

# Configure overrides for specific fields
converter.register_structure_hook(datetime, lambda s, _: datetime.fromisoformat(s))
converter.register_unstructure_hook(datetime, lambda dt: dt.isoformat())

# Create overrides for field-level customization
overrides = {
    "timestamp": override(rename="event_time"),
    "description": override(omit_if_default=True)
}

# Generate functions with overrides
structure_event = make_dict_structure_fn(
    Event, 
    converter, 
    _attrib_overrides=overrides
)
unstructure_event = make_dict_unstructure_fn(
    Event, 
    converter, 
    _attrib_overrides=overrides
)

# Data uses "event_time" instead of "timestamp"
event_data = {
    "name": "Meeting",
    "event_time": "2024-01-01T10:00:00"
    # description omitted when it's the default value
}

event = structure_event(event_data)

High-Performance Iterable Processing

from cattrs import Converter
from cattrs.gen import make_iterable_unstructure_fn, make_dict_structure_fn
from attrs import define
from typing import List

@define
class Product:
    name: str
    price: float
    in_stock: bool

converter = Converter()

# Generate optimized functions for lists of products
structure_product = make_dict_structure_fn(Product, converter)
unstructure_products = make_iterable_unstructure_fn(List[Product], converter)

# Process large lists efficiently
products = [
    Product("Laptop", 999.99, True),
    Product("Mouse", 29.99, False),
    # ... thousands of products
]

# Optimized bulk unstructuring
products_data = unstructure_products(products)

# Individual structuring using the optimized function
structured_products = [structure_product(data) for data in products_data]

Mapping and Complex Type Generation

from cattrs import Converter
from cattrs.gen import make_mapping_structure_fn, make_mapping_unstructure_fn
from attrs import define
from typing import Dict

@define
class Config:
    host: str
    port: int
    ssl: bool

converter = Converter()

# Generate functions for mappings with Config values
structure_config_map = make_mapping_structure_fn(Dict[str, Config], converter)
unstructure_config_map = make_mapping_unstructure_fn(Dict[str, Config], converter)

# Use with configuration mappings
configs = {
    "development": Config("localhost", 8000, False),
    "production": Config("prod.example.com", 443, True)
}

# Efficient mapping operations
config_data = unstructure_config_map(configs)
configs_copy = structure_config_map(config_data)

Integration with Converter Hooks

from cattrs import Converter
from cattrs.gen import make_dict_structure_fn
from attrs import define

@define
class APIResponse:
    status: str
    data: dict
    timestamp: int

converter = Converter()

# Register the generated function as a hook for automatic use
structure_response = make_dict_structure_fn(APIResponse, converter)
converter.register_structure_hook(APIResponse, structure_response)

# Now the converter uses the optimized function automatically
response_data = {
    "status": "success", 
    "data": {"result": "ok"}, 
    "timestamp": 1640995200
}

response = converter.structure(response_data, APIResponse)  # Uses optimized function

Performance Considerations

Generated functions provide significant performance improvements:

  • Structure functions: 2-5x faster than generic converter methods
  • Unstructure functions: 2-4x faster for complex objects
  • Bulk operations: Even greater improvements for lists and mappings
  • Memory efficiency: Reduced allocation overhead for repeated operations

Best practices:

  • Generate functions once and reuse them
  • Use overrides to avoid runtime field processing
  • Consider generating functions for performance-critical code paths
  • Combine with converter hooks for seamless integration

Types

from typing import TypeVar, Callable, Any, Dict, List, Tuple, Type
from cattrs.gen import AttributeOverride

T = TypeVar('T')

# Function type aliases
StructureFn = Callable[[Dict[str, Any]], T]
UnstructureFn = Callable[[T], Dict[str, Any]]
HeteroTupleUnstructureFn = Callable[[Tuple], Tuple]
IterableUnstructureFn = Callable[[List[T]], List[Any]]
MappingUnstructureFn = Callable[[Dict[Any, T]], Dict[Any, Any]]

# Override types
AttributeOverrides = Dict[str, AttributeOverride]
OverrideMapping = Dict[str, Any]

Install with Tessl CLI

npx tessl i tessl/pypi-cattrs

docs

code-generation.md

core-api.md

error-handling.md

index.md

preconf-converters.md

strategies.md

tile.json