CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-dataclass-factory

A comprehensive dataclass instance creation library that enables bidirectional conversion between dictionaries and dataclass instances.

Pending
Overview
Eval results
Files

naming.mddocs/

Naming Policies

Flexible naming convention conversion system for handling different field naming styles between Python code and external data formats. Supports common naming patterns used in APIs, configuration files, and data interchange formats.

Capabilities

NameStyle Enum

Enumeration defining supported naming conventions with their string representations.

class NameStyle(Enum):
    snake = "snake_case"
    kebab = "kebab-case"
    camel_lower = "camelCaseLower"  
    camel = "CamelCase"

Name Conversion Functions

Core functions for converting between different naming styles and handling field name transformations.

def convert_name(
    name: str,
    trim_trailing_underscore: bool = True,
    naming_policy: NameStyle = None
) -> str:
    """
    Convert a field name according to the specified policy.
    
    Args:
        name: The original field name to convert
        trim_trailing_underscore: Remove trailing underscore if present
        naming_policy: Target naming style to convert to
        
    Returns:
        Converted field name according to the policy
    """

def split_name(name: str) -> List[str]:
    """
    Split a name into component words by underscores.
    
    Args:
        name: Name to split
        
    Returns:
        List of word components
    """

def title(name: str) -> str:
    """
    Capitalize the first letter of a name.
    
    Args:
        name: Name to capitalize
        
    Returns:
        Name with first letter capitalized
    """

def snake(name: str) -> str:
    """
    Convert name to snake_case format.
    
    Args:
        name: Name to convert
        
    Returns:
        snake_case formatted name
    """

def kebab(name: str) -> str:
    """
    Convert name to kebab-case format.
    
    Args:
        name: Name to convert
        
    Returns:
        kebab-case formatted name  
    """

def camel_lower(name: str) -> str:
    """
    Convert name to camelCase format (lowercase first letter).
    
    Args:
        name: Name to convert
        
    Returns:
        camelCase formatted name
    """

def camel(name: str) -> str:
    """
    Convert name to CamelCase format (uppercase first letter).
    
    Args:
        name: Name to convert
        
    Returns:
        CamelCase formatted name
    """

Usage Examples

Basic Naming Policy Application

from dataclasses import dataclass
from dataclass_factory import ParserFactory, SerializerFactory, NameStyle

@dataclass
class UserProfile:
    first_name: str
    last_name: str
    email_address: str
    is_active: bool

# Parsing from camelCase JSON (common in JavaScript APIs)
parser_factory = ParserFactory(
    name_styles={UserProfile: NameStyle.camel_lower}
)
parser = parser_factory.get_parser(UserProfile)

camel_case_data = {
    "firstName": "John",
    "lastName": "Doe", 
    "emailAddress": "john.doe@example.com",
    "isActive": True
}

user = parser(camel_case_data)
# Result: UserProfile(first_name="John", last_name="Doe", ...)

# Serializing to kebab-case (common in HTML attributes/CSS)
serializer_factory = SerializerFactory(
    name_styles={UserProfile: NameStyle.kebab}
)
serializer = serializer_factory.get_serializer(UserProfile)

kebab_case_data = serializer(user)
# Result: {
#     "first-name": "John",
#     "last-name": "Doe",
#     "email-address": "john.doe@example.com", 
#     "is-active": True
# }

Multiple Classes with Different Policies

from dataclasses import dataclass
from dataclass_factory import ParserFactory, NameStyle

@dataclass
class ApiRequest:
    user_id: int
    request_type: str
    
@dataclass  
class DatabaseRecord:
    record_id: str
    created_at: str

# Different naming policies per class
parser_factory = ParserFactory(
    name_styles={
        ApiRequest: NameStyle.camel_lower,    # For JSON APIs
        DatabaseRecord: NameStyle.snake       # For database consistency
    }
)

api_parser = parser_factory.get_parser(ApiRequest)
db_parser = parser_factory.get_parser(DatabaseRecord)

# Parse camelCase API data
api_data = {"userId": 123, "requestType": "GET"}
request = api_parser(api_data)

# Parse snake_case database data  
db_data = {"record_id": "abc123", "created_at": "2023-12-25"}
record = db_parser(db_data)

Name Conversion Usage

Note: Direct name conversion functions are not part of the public API. Name conversion should be done through ParserFactory and SerializerFactory using the name_styles parameter.

from dataclass_factory import ParserFactory, SerializerFactory, NameStyle
from dataclasses import dataclass

@dataclass
class UserData:
    user_profile_id: int
    class_: str  # Trailing underscore to avoid Python keyword

# Example: Convert from camelCase input to dataclass
parser = ParserFactory(name_styles={UserData: NameStyle.camel_lower})
user_parser = parser.get_parser(UserData)

camel_data = {
    "userProfileId": 123,
    "class": "admin"  # Input uses camelCase
}

user = user_parser(camel_data)
# Result: UserData(user_profile_id=123, class_="admin")

# Example: Convert to kebab-case output  
serializer = SerializerFactory(name_styles={UserData: NameStyle.kebab})
user_serializer = serializer.get_serializer(UserData)

kebab_data = user_serializer(user)
# Result: {"user-profile-id": 123, "class": "admin"}

Advanced Configuration

from dataclasses import dataclass
from dataclass_factory import ParserFactory, SerializerFactory, NameStyle

@dataclass
class ConfigData:
    api_key_: str          # Trailing underscore to avoid 'api_key' conflicts
    max_retry_count: int
    enable_logging: bool

# Parse from environment-style config (SCREAMING_SNAKE_CASE converted to snake_case)
class EnvironmentNameStyle:
    """Custom handling for environment variable style names"""
    
    @staticmethod
    def convert_env_name(name: str) -> str:
        return name.lower().replace('_', '_')  # Already snake_case

# Using with custom preprocessing
parser_factory = ParserFactory(
    trim_trailing_underscore=True,
    name_styles={ConfigData: NameStyle.snake}
)

config_data = {
    "api_key": "secret123",        # Will map to api_key_ field
    "max_retry_count": 5,
    "enable_logging": True
}

config = parser_factory.get_parser(ConfigData)(config_data)
# Result: ConfigData(api_key_="secret123", max_retry_count=5, enable_logging=True)

Constants

NAMING_FUNC: Dict[NameStyle, Callable[[str], str]]

Mapping of NameStyle enum values to their corresponding conversion functions. Used internally by the conversion system but available for custom usage.

Naming Style Guide

snake_case (Python standard)

  • Use for: Python field names, database columns, configuration files
  • Format: user_name, email_address, is_active
  • Best for: Internal Python code, database schemas

kebab-case

  • Use for: HTML attributes, CSS properties, URL parameters
  • Format: user-name, email-address, is-active
  • Best for: Web frontends, configuration files, command-line options

camelCase (JavaScript standard)

  • Use for: JSON APIs, JavaScript interop, mobile app APIs
  • Format: userName, emailAddress, isActive
  • Best for: REST APIs, JSON data interchange, frontend integration

CamelCase/PascalCase

  • Use for: Class names, type names, some API conventions
  • Format: UserName, EmailAddress, IsActive
  • Best for: Type definitions, class-based APIs, XML elements

Performance Considerations

  • Name conversion is cached within ParserFactory/SerializerFactory instances
  • Conversion functions are lightweight and optimized for repeated use
  • trim_trailing_underscore has minimal performance impact
  • For maximum performance, reuse factory instances rather than creating new ones

Install with Tessl CLI

npx tessl i tessl/pypi-dataclass-factory

docs

index.md

naming.md

parsing.md

serialization.md

tile.json