0
# Naming Policies
1
2
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.
3
4
## Capabilities
5
6
### NameStyle Enum
7
8
Enumeration defining supported naming conventions with their string representations.
9
10
```python { .api }
11
class NameStyle(Enum):
12
snake = "snake_case"
13
kebab = "kebab-case"
14
camel_lower = "camelCaseLower"
15
camel = "CamelCase"
16
```
17
18
### Name Conversion Functions
19
20
Core functions for converting between different naming styles and handling field name transformations.
21
22
```python { .api }
23
def convert_name(
24
name: str,
25
trim_trailing_underscore: bool = True,
26
naming_policy: NameStyle = None
27
) -> str:
28
"""
29
Convert a field name according to the specified policy.
30
31
Args:
32
name: The original field name to convert
33
trim_trailing_underscore: Remove trailing underscore if present
34
naming_policy: Target naming style to convert to
35
36
Returns:
37
Converted field name according to the policy
38
"""
39
40
def split_name(name: str) -> List[str]:
41
"""
42
Split a name into component words by underscores.
43
44
Args:
45
name: Name to split
46
47
Returns:
48
List of word components
49
"""
50
51
def title(name: str) -> str:
52
"""
53
Capitalize the first letter of a name.
54
55
Args:
56
name: Name to capitalize
57
58
Returns:
59
Name with first letter capitalized
60
"""
61
62
def snake(name: str) -> str:
63
"""
64
Convert name to snake_case format.
65
66
Args:
67
name: Name to convert
68
69
Returns:
70
snake_case formatted name
71
"""
72
73
def kebab(name: str) -> str:
74
"""
75
Convert name to kebab-case format.
76
77
Args:
78
name: Name to convert
79
80
Returns:
81
kebab-case formatted name
82
"""
83
84
def camel_lower(name: str) -> str:
85
"""
86
Convert name to camelCase format (lowercase first letter).
87
88
Args:
89
name: Name to convert
90
91
Returns:
92
camelCase formatted name
93
"""
94
95
def camel(name: str) -> str:
96
"""
97
Convert name to CamelCase format (uppercase first letter).
98
99
Args:
100
name: Name to convert
101
102
Returns:
103
CamelCase formatted name
104
"""
105
```
106
107
### Usage Examples
108
109
#### Basic Naming Policy Application
110
111
```python
112
from dataclasses import dataclass
113
from dataclass_factory import ParserFactory, SerializerFactory, NameStyle
114
115
@dataclass
116
class UserProfile:
117
first_name: str
118
last_name: str
119
email_address: str
120
is_active: bool
121
122
# Parsing from camelCase JSON (common in JavaScript APIs)
123
parser_factory = ParserFactory(
124
name_styles={UserProfile: NameStyle.camel_lower}
125
)
126
parser = parser_factory.get_parser(UserProfile)
127
128
camel_case_data = {
129
"firstName": "John",
130
"lastName": "Doe",
131
"emailAddress": "john.doe@example.com",
132
"isActive": True
133
}
134
135
user = parser(camel_case_data)
136
# Result: UserProfile(first_name="John", last_name="Doe", ...)
137
138
# Serializing to kebab-case (common in HTML attributes/CSS)
139
serializer_factory = SerializerFactory(
140
name_styles={UserProfile: NameStyle.kebab}
141
)
142
serializer = serializer_factory.get_serializer(UserProfile)
143
144
kebab_case_data = serializer(user)
145
# Result: {
146
# "first-name": "John",
147
# "last-name": "Doe",
148
# "email-address": "john.doe@example.com",
149
# "is-active": True
150
# }
151
```
152
153
#### Multiple Classes with Different Policies
154
155
```python
156
from dataclasses import dataclass
157
from dataclass_factory import ParserFactory, NameStyle
158
159
@dataclass
160
class ApiRequest:
161
user_id: int
162
request_type: str
163
164
@dataclass
165
class DatabaseRecord:
166
record_id: str
167
created_at: str
168
169
# Different naming policies per class
170
parser_factory = ParserFactory(
171
name_styles={
172
ApiRequest: NameStyle.camel_lower, # For JSON APIs
173
DatabaseRecord: NameStyle.snake # For database consistency
174
}
175
)
176
177
api_parser = parser_factory.get_parser(ApiRequest)
178
db_parser = parser_factory.get_parser(DatabaseRecord)
179
180
# Parse camelCase API data
181
api_data = {"userId": 123, "requestType": "GET"}
182
request = api_parser(api_data)
183
184
# Parse snake_case database data
185
db_data = {"record_id": "abc123", "created_at": "2023-12-25"}
186
record = db_parser(db_data)
187
```
188
189
#### Name Conversion Usage
190
191
**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.
192
193
```python
194
from dataclass_factory import ParserFactory, SerializerFactory, NameStyle
195
from dataclasses import dataclass
196
197
@dataclass
198
class UserData:
199
user_profile_id: int
200
class_: str # Trailing underscore to avoid Python keyword
201
202
# Example: Convert from camelCase input to dataclass
203
parser = ParserFactory(name_styles={UserData: NameStyle.camel_lower})
204
user_parser = parser.get_parser(UserData)
205
206
camel_data = {
207
"userProfileId": 123,
208
"class": "admin" # Input uses camelCase
209
}
210
211
user = user_parser(camel_data)
212
# Result: UserData(user_profile_id=123, class_="admin")
213
214
# Example: Convert to kebab-case output
215
serializer = SerializerFactory(name_styles={UserData: NameStyle.kebab})
216
user_serializer = serializer.get_serializer(UserData)
217
218
kebab_data = user_serializer(user)
219
# Result: {"user-profile-id": 123, "class": "admin"}
220
```
221
222
#### Advanced Configuration
223
224
```python
225
from dataclasses import dataclass
226
from dataclass_factory import ParserFactory, SerializerFactory, NameStyle
227
228
@dataclass
229
class ConfigData:
230
api_key_: str # Trailing underscore to avoid 'api_key' conflicts
231
max_retry_count: int
232
enable_logging: bool
233
234
# Parse from environment-style config (SCREAMING_SNAKE_CASE converted to snake_case)
235
class EnvironmentNameStyle:
236
"""Custom handling for environment variable style names"""
237
238
@staticmethod
239
def convert_env_name(name: str) -> str:
240
return name.lower().replace('_', '_') # Already snake_case
241
242
# Using with custom preprocessing
243
parser_factory = ParserFactory(
244
trim_trailing_underscore=True,
245
name_styles={ConfigData: NameStyle.snake}
246
)
247
248
config_data = {
249
"api_key": "secret123", # Will map to api_key_ field
250
"max_retry_count": 5,
251
"enable_logging": True
252
}
253
254
config = parser_factory.get_parser(ConfigData)(config_data)
255
# Result: ConfigData(api_key_="secret123", max_retry_count=5, enable_logging=True)
256
```
257
258
## Constants
259
260
```python { .api }
261
NAMING_FUNC: Dict[NameStyle, Callable[[str], str]]
262
```
263
264
Mapping of NameStyle enum values to their corresponding conversion functions. Used internally by the conversion system but available for custom usage.
265
266
## Naming Style Guide
267
268
### snake_case (Python standard)
269
- **Use for**: Python field names, database columns, configuration files
270
- **Format**: `user_name`, `email_address`, `is_active`
271
- **Best for**: Internal Python code, database schemas
272
273
### kebab-case
274
- **Use for**: HTML attributes, CSS properties, URL parameters
275
- **Format**: `user-name`, `email-address`, `is-active`
276
- **Best for**: Web frontends, configuration files, command-line options
277
278
### camelCase (JavaScript standard)
279
- **Use for**: JSON APIs, JavaScript interop, mobile app APIs
280
- **Format**: `userName`, `emailAddress`, `isActive`
281
- **Best for**: REST APIs, JSON data interchange, frontend integration
282
283
### CamelCase/PascalCase
284
- **Use for**: Class names, type names, some API conventions
285
- **Format**: `UserName`, `EmailAddress`, `IsActive`
286
- **Best for**: Type definitions, class-based APIs, XML elements
287
288
## Performance Considerations
289
290
- Name conversion is cached within ParserFactory/SerializerFactory instances
291
- Conversion functions are lightweight and optimized for repeated use
292
- `trim_trailing_underscore` has minimal performance impact
293
- For maximum performance, reuse factory instances rather than creating new ones