Composable complex class support for attrs and dataclasses with (un)structuring and validation.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
The fundamental cattrs API for converting between structured and unstructured data. This module provides the primary functions and classes that form the backbone of cattrs functionality.
Functions that use the global converter instance for simple, direct usage without requiring converter instantiation.
def structure(obj, cl):
"""
Convert unstructured data to structured data using the global converter.
Parameters:
- obj: The unstructured data to convert
- cl: The class or type to structure into
Returns:
Structured instance of the specified class
"""
def unstructure(obj, unstructure_as=None):
"""
Convert structured data to unstructured data using the global converter.
Parameters:
- obj: The structured object to convert
- unstructure_as: Optional type to unstructure as
Returns:
Unstructured data (typically dict or primitive types)
"""
def structure_attrs_fromdict(dict_obj, cl):
"""
Structure attrs classes from dictionaries using the global converter.
Parameters:
- dict_obj: Dictionary to structure from
- cl: attrs class to structure into
Returns:
Instance of the attrs class
"""
def structure_attrs_fromtuple(tuple_obj, cl):
"""
Structure attrs classes from tuples using the global converter.
Parameters:
- tuple_obj: Tuple to structure from
- cl: attrs class to structure into
Returns:
Instance of the attrs class
"""Core converter classes that provide the main structuring and unstructuring functionality.
class BaseConverter:
"""
Base class for all converters that handles structured/unstructured data conversion.
Provides the foundation for the converter system but should not be instantiated directly.
"""
def __init__(self):
"""Initialize the base converter."""
class Converter(BaseConverter):
"""
Main converter class with specialized un/structuring functions and advanced features.
Provides customizable hooks, strategies, and optimization options for data conversion.
"""
def __init__(
self,
dict_factory=dict,
unstruct_strat=UnstructureStrategy.AS_DICT,
omit_if_default=False,
forbid_extra_keys=False,
type_overrides=None,
unstruct_collection_overrides=None,
prefer_attrib_converters=False,
detailed_validation=True,
unstructure_fallback_factory=lambda _: identity,
structure_fallback_factory=lambda t: raise_error(None, t),
use_alias=False
):
"""
Initialize a converter with customization options.
Parameters:
- dict_factory: Factory function for creating dictionaries
- unstruct_strat: Default unstructuring strategy
- omit_if_default: Omit fields with default values during unstructuring
- forbid_extra_keys: Whether to forbid extra keys during structuring
- type_overrides: Mapping of type overrides for attribute handling
- unstruct_collection_overrides: Mapping of collection unstructure overrides
- prefer_attrib_converters: Use attribute-level converters when available
- detailed_validation: Enable detailed validation error messages
- unstructure_fallback_factory: Factory for unstructuring hooks when no match
- structure_fallback_factory: Factory for structuring hooks when no match
- use_alias: Use field alias instead of field name as dictionary key
"""
def structure(self, obj, cl):
"""
Convert unstructured data to a structured class instance.
Parameters:
- obj: Unstructured data to convert
- cl: Class or type to structure into
Returns:
Instance of the specified class
"""
def unstructure(self, obj, unstructure_as=None):
"""
Convert a structured object to unstructured data.
Parameters:
- obj: Structured object to convert
- unstructure_as: Optional type to unstructure as
Returns:
Unstructured data representation
"""
def structure_attrs_fromdict(self, dict_obj, cl):
"""Structure attrs classes from dictionaries."""
def structure_attrs_fromtuple(self, tuple_obj, cl):
"""Structure attrs classes from tuples."""
# Type alias for backward compatibility
GenConverter = ConverterFunctions for registering custom structuring and unstructuring hooks with converters.
def register_structure_hook(cl, func=None):
"""
Register a structure hook for a specific type on the global converter.
Parameters:
- cl: The class or type to register the hook for
- func: The hook function to register (can be used as decorator if None)
Returns:
The hook function (when used as decorator) or None
"""
def register_structure_hook_func(check_func, func):
"""
Register a structure hook using a predicate function on the global converter.
Parameters:
- check_func: Function that returns True for types this hook handles
- func: The hook function to register
"""
def register_unstructure_hook(cl, func=None):
"""
Register an unstructure hook for a specific type on the global converter.
Parameters:
- cl: The class or type to register the hook for
- func: The hook function to register (can be used as decorator if None)
Returns:
The hook function (when used as decorator) or None
"""
def register_unstructure_hook_func(check_func, func):
"""
Register an unstructure hook using a predicate function on the global converter.
Parameters:
- check_func: Function that returns True for types this hook handles
- func: The hook function to register
"""
def get_structure_hook(cl, cache_result=True):
"""
Get the structure hook for a given type from the global converter.
Parameters:
- cl: The class or type to get the hook for
- cache_result: Whether to cache the result for performance
Returns:
The structure hook function for the type
"""
def get_unstructure_hook(cl, cache_result=True):
"""
Get the unstructure hook for a given type from the global converter.
Parameters:
- cl: The class or type to get the hook for
- cache_result: Whether to cache the result for performance
Returns:
The unstructure hook function for the type
"""The global converter instance used by module-level functions.
global_converter: Converter
"""The global converter instance used by module-level functions."""from cattrs import structure, unstructure
from attrs import define
from typing import List
@define
class User:
name: str
age: int
tags: List[str]
# Create structured data
user = User(name="Alice", age=30, tags=["admin", "user"])
# Unstructure to dictionary
user_dict = unstructure(user)
# Result: {'name': 'Alice', 'age': 30, 'tags': ['admin', 'user']}
# Structure back to class
user_copy = structure(user_dict, User)
# Result: User(name='Alice', age=30, tags=['admin', 'user'])from cattrs import Converter, UnstructureStrategy
# Create custom converter with specific settings
converter = Converter(
dict_factory=dict,
unstruct_strat=UnstructureStrategy.AS_DICT,
forbid_extra_keys=True
)
# Use custom converter
data = converter.unstructure(user)
user_copy = converter.structure(data, User)from cattrs import register_structure_hook, register_unstructure_hook
from datetime import datetime
# Register hooks for datetime handling
def structure_datetime(timestamp_str, _):
return datetime.fromisoformat(timestamp_str)
def unstructure_datetime(dt):
return dt.isoformat()
register_structure_hook(datetime, structure_datetime)
register_unstructure_hook(datetime, unstructure_datetime)
# Now datetime objects will be handled automatically
@define
class Event:
name: str
timestamp: datetime
event = Event("Meeting", datetime.now())
event_dict = unstructure(event) # timestamp becomes ISO string
event_copy = structure(event_dict, Event) # string becomes datetimefrom typing import TypeVar, Any, Callable, Dict, Optional, Mapping
from enum import Enum
from cattrs.fns import identity, raise_error
from cattrs.gen import AttributeOverride
T = TypeVar('T')
class UnstructureStrategy(Enum):
"""Enum defining unstructuring strategies."""
AS_DICT = "AS_DICT"
AS_TUPLE = "AS_TUPLE"
# Hook function types
StructureHook = Callable[[Any, type[T]], T]
UnstructureHook = Callable[[T], Any]
PredicateFunc = Callable[[type], bool]
HookFactory = Callable[[type], Any]Install with Tessl CLI
npx tessl i tessl/pypi-cattrs