-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
codegen to create pydantic classes from dict
- Loading branch information
1 parent
d460e16
commit 5578068
Showing
2 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
from typing import Any | ||
from pydantic import BaseModel, Field | ||
|
||
from dcpy.utils.string import to_snake, to_camel | ||
|
||
|
||
def pydantic_class_from_dict(class_name: str, obj: dict[str, Any]) -> str: | ||
str = f"class {class_name}(BaseModel):" | ||
subclasses = [] | ||
|
||
for field in obj: | ||
str += "\n " | ||
val = obj[field] | ||
if isinstance(val, dict): | ||
type_name = to_camel(field) | ||
subclasses.append(pydantic_class_from_dict(type_name, val)) | ||
elif isinstance(val, list) and (len(val) > 0): | ||
class_name = to_camel(field) | ||
type_name = f"list[{class_name}]" | ||
subclasses.append(pydantic_class_from_dict(class_name, val[0])) | ||
else: | ||
type_name = type(val).__name__ | ||
field_name = to_snake(field) | ||
if field != field_name: | ||
str += f'{field_name}: {type_name} = Field(alias="{field}")' | ||
else: | ||
str += f"{field_name}: {type_name}" | ||
|
||
subclasses.append(str) | ||
return "\n\n".join(subclasses) | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,15 @@ | ||
import re | ||
|
||
|
||
def camel_to_snake(s: str) -> str: | ||
def to_camel(s: str) -> str: | ||
s = re.sub("[^0-9a-zA-Z]+", "_", s) | ||
s = re.sub("_+", "_", s) | ||
return "".join(x.capitalize() for x in s.lower().split("_")) | ||
|
||
|
||
def to_snake(s: str) -> str: | ||
s = re.sub("[^0-9a-zA-Z]+", "_", s) | ||
s = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", s) | ||
s = re.sub("_+", "_", s) | ||
s = s.strip("_") | ||
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s).lower() |