CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyserde

Yet another serialization library on top of dataclasses

Pending
Overview
Eval results
Files

type-system.mddocs/

Type System Compatibility

Comprehensive type introspection and compatibility utilities for working with Python's type system, generics, complex nested types, and modern typing features. This module provides the foundation for pyserde's extensive type support.

Capabilities

Type Predicates

Functions to test for specific type categories and patterns.

def is_union(typ) -> bool:
    """Test if type is a union type (Union[A, B] or A | B)."""

def is_opt(typ) -> bool:
    """Test if type is Optional (Union[T, None])."""

def is_list(typ) -> bool:
    """Test if type is a list type."""

def is_set(typ) -> bool:
    """Test if type is a set type."""

def is_tuple(typ) -> bool:
    """Test if type is a tuple type."""

def is_dict(typ) -> bool:
    """Test if type is a dict type."""

def is_bare_list(typ) -> bool:
    """Test if type is unparameterized list."""

def is_bare_set(typ) -> bool:
    """Test if type is unparameterized set."""

def is_bare_tuple(typ) -> bool:
    """Test if type is unparameterized tuple."""

def is_bare_dict(typ) -> bool:
    """Test if type is unparameterized dict."""

def is_variable_tuple(typ) -> bool:
    """Test if type is variable-length tuple (Tuple[T, ...])."""

def is_frozen_set(typ) -> bool:
    """Test if type is frozenset."""

def is_default_dict(typ) -> bool:
    """Test if type is defaultdict."""

def is_none(typ) -> bool:
    """Test if type is None/NoneType."""

def is_any(typ) -> bool:
    """Test if type is typing.Any."""

def is_generic(typ) -> bool:
    """Test if type is a generic type."""

def is_literal(typ) -> bool:
    """Test if type is typing.Literal."""

def is_class_var(typ) -> bool:
    """Test if type is typing.ClassVar."""

def is_primitive(typ) -> bool:
    """Test if type is a primitive type (int, float, str, bool)."""

def is_enum(typ) -> bool:
    """Test if type is an Enum."""

def is_datetime(typ) -> bool:
    """Test if type is a datetime-related type."""

def is_str_serializable(typ) -> bool:
    """Test if type can be serialized as string (UUID, Path, etc.)."""

Type Introspection

Functions for extracting type information and metadata.

def get_origin(typ):
    """
    Get origin type from generic type.
    
    Parameters:
    - typ: Type to analyze
    
    Returns:
    Origin type (e.g., list from List[int])
    """

def get_args(typ):
    """
    Get type arguments from generic type.
    
    Parameters:
    - typ: Type to analyze
    
    Returns:
    Tuple of type arguments (e.g., (int,) from List[int])
    """

def typename(typ) -> str:
    """
    Get string representation of type.
    
    Parameters:
    - typ: Type to represent
    
    Returns:
    String name of the type
    """

def type_args(typ):
    """
    Get type arguments with fallback handling.
    
    Parameters:
    - typ: Type to analyze
    
    Returns:
    Type arguments or empty tuple if none
    """

def dataclass_fields(cls):
    """
    Get resolved dataclass fields with type information.
    
    Parameters:
    - cls: Dataclass to analyze
    
    Returns:
    Dictionary of field names to field objects
    """

Type Iteration

Functions for traversing and analyzing complex type structures.

def iter_types(cls):
    """
    Recursively iterate over all field types in a dataclass.
    
    Parameters:
    - cls: Dataclass to analyze
    
    Yields:
    Type objects found in the class hierarchy
    """

def iter_unions(cls):
    """
    Find all union types in a dataclass.
    
    Parameters:
    - cls: Dataclass to analyze
    
    Yields:
    Union type objects found in the class
    """

def iter_literals(cls):
    """
    Find all literal types in a dataclass.
    
    Parameters:
    - cls: Dataclass to analyze
    
    Yields:
    Literal type objects found in the class
    """

Generic Type Support

Functions for working with generic types and type variables.

def get_type_var_names(cls) -> List[str]:
    """
    Get type variable names from generic class.
    
    Parameters:
    - cls: Generic class to analyze
    
    Returns:
    List of type variable names
    """

def find_generic_arg(typ, type_var) -> int:
    """
    Find position of type variable in generic type.
    
    Parameters:
    - typ: Generic type to search
    - type_var: Type variable to find
    
    Returns:
    Index of type variable or -1 if not found
    """

def get_generic_arg(typ, type_var):
    """
    Resolve generic type argument for a type variable.
    
    Parameters:
    - typ: Generic type instance  
    - type_var: Type variable to resolve
    
    Returns:
    Resolved type argument
    """

Exception Handling

Exception classes for type system errors.

class SerdeError(Exception):
    """Base exception for serde errors."""

class SerdeSkip(Exception):
    """Exception to skip field serialization in custom serializers."""

class UserError(Exception):
    """Wrapper for errors in user-defined custom serializers/deserializers."""

Usage Examples

Type Checking

from serde.compat import is_union, is_opt, is_list, get_origin, get_args
from typing import Union, Optional, List

# Test union types
print(is_union(Union[int, str]))  # True
print(is_union(int))              # False

# Test optional types  
print(is_opt(Optional[str]))      # True
print(is_opt(Union[str, None]))   # True
print(is_opt(str))                # False

# Test container types
print(is_list(List[int]))         # True
print(is_list(list))              # True
print(is_list(int))               # False

# Extract type information
list_type = List[str]
print(get_origin(list_type))      # <class 'list'>
print(get_args(list_type))        # (<class 'str'>,)

Working with Generic Types

from serde import serde
from serde.compat import get_type_var_names, get_generic_arg
from typing import TypeVar, Generic, List

T = TypeVar('T')

@serde
class Container(Generic[T]):
    items: List[T]

# Analyze generic type
print(get_type_var_names(Container))  # ['T']

# Work with concrete generic instances
IntContainer = Container[int]
print(get_generic_arg(IntContainer, T))  # <class 'int'>

Type Iteration

from serde import serde
from serde.compat import iter_types, iter_unions
from typing import Union, List, Dict

@serde
class ComplexData:
    id: int
    name: str
    tags: List[str]
    metadata: Dict[str, Union[str, int]]
    optional_field: Union[str, None]

# Iterate over all types
for typ in iter_types(ComplexData):
    print(f"Found type: {typ}")

# Find union types specifically  
for union_typ in iter_unions(ComplexData):
    print(f"Found union: {union_typ}")

Custom Type Handling

from serde import serde, field
from serde.compat import is_datetime, typename
from datetime import datetime, date
from typing import Any

def custom_datetime_handler(obj: Any) -> str:
    """Custom serializer that handles any datetime-like object."""
    if is_datetime(type(obj)):
        return obj.isoformat()
    return str(obj)

@serde
class Event:
    name: str
    created_at: datetime = field(serializer=custom_datetime_handler)
    event_date: date = field(serializer=custom_datetime_handler)

event = Event("Meeting", datetime.now(), date.today())
# Both datetime fields will be serialized using the custom handler

Advanced Type Analysis

from serde.compat import *
from typing import Dict, List, Union, Optional, Literal, Any
from dataclasses import dataclass

# Analyze complex nested types
complex_type = Dict[str, List[Union[int, str, Optional[bool]]]]

print(f"Is dict: {is_dict(complex_type)}")
print(f"Origin: {get_origin(complex_type)}")
print(f"Args: {get_args(complex_type)}")

# Check for specific type patterns
value_type = get_args(complex_type)[1]  # List[Union[int, str, Optional[bool]]]
print(f"Is list: {is_list(value_type)}")

inner_union = get_args(value_type)[0]   # Union[int, str, Optional[bool]]
print(f"Is union: {is_union(inner_union)}")

# Test literal types
status_type = Literal["active", "inactive", "pending"]
print(f"Is literal: {is_literal(status_type)}")

# Test Any type
print(f"Is any: {is_any(Any)}")

Install with Tessl CLI

npx tessl i tessl/pypi-pyserde

docs

core-serialization.md

field-configuration.md

format-modules.md

index.md

type-system.md

union-handling.md

tile.json