Skip to content

Commit ea0d381

Browse files
committed
added support for pascal case on aliases functions
1 parent fd29e0c commit ea0d381

File tree

2 files changed

+46
-5
lines changed

2 files changed

+46
-5
lines changed

datamodel/aliases/__init__.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,17 @@ def to_snakecase(name: str) -> str:
1010
Convert a CamelCase or PascalCase string into snake_case.
1111
Example: "EmailAddress" -> "email_address"
1212
"""
13-
import re
1413
# Insert underscores before capital letters, then lower-case
1514
s1 = _RE_FIRST_CAP.sub(r"\1_\2", name)
1615
return _RE_ALL_CAPS.sub(r"\1_\2", s1).lower()
16+
17+
18+
def to_pascalcase(s: str) -> str:
19+
"""
20+
Convert a snake_case string into PascalCase.
21+
Example:
22+
store_id -> StoreId
23+
email_address -> EmailAddress
24+
"""
25+
parts = s.split("_")
26+
return "".join(word.capitalize() for word in parts)

examples/test_aliases.py

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import List, Optional
22
from datamodel import BaseModel, Field
3-
from datamodel.aliases import to_snakecase
3+
from datamodel.aliases import to_snakecase, to_pascalcase
44

55

66
class Store(BaseModel):
@@ -13,6 +13,37 @@ class Meta:
1313
as_objects = True
1414
alias_function = to_snakecase
1515

16-
# Example Usage:
17-
store = Store(EmailAddress="[email protected]", Status="ACTIVE", StoreId=1)
18-
print(store)
16+
17+
18+
class ExampleModel(BaseModel):
19+
# Here, our Python fields are declared in PascalCase.
20+
StoreId: int = Field(primary_key=True)
21+
EmailAddress: str
22+
Status: str
23+
24+
class Meta:
25+
strict = True
26+
as_objects = True
27+
# Our alias_function now transforms from the incoming snake_case to PascalCase.
28+
# So if user passes `store_id`, we transform it to `StoreId`.
29+
alias_function = to_pascalcase
30+
31+
def demo():
32+
store = Store(EmailAddress="[email protected]", Status="ACTIVE", StoreId=1)
33+
print("StoreId =>", store.store_id)
34+
print("EmailAddress =>", store.email_address)
35+
# The user input is using snake_case:
36+
model = ExampleModel(
37+
store_id=123,
38+
email_address="[email protected]",
39+
status="ACTIVE"
40+
)
41+
# Internally, we have PascalCase attributes:
42+
print("StoreId =>", model.StoreId)
43+
print("EmailAddress =>", model.EmailAddress)
44+
print("Status =>", model.Status)
45+
# Check the actual model
46+
print(model)
47+
48+
if __name__ == "__main__":
49+
demo()

0 commit comments

Comments
 (0)