Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix to_snake conversion #8316

Merged
merged 1 commit into from Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions pydantic/alias_generators.py
Expand Up @@ -39,6 +39,12 @@ def to_snake(camel: str) -> str:
Returns:
The converted string in snake_case.
"""
snake = re.sub(r'([a-zA-Z])([0-9])', lambda m: f'{m.group(1)}_{m.group(2)}', camel)
snake = re.sub(r'([a-z0-9])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
# Handle the sequence of uppercase letters followed by a lowercase letter
snake = re.sub(r'([A-Z]+)([A-Z][a-z])', lambda m: f'{m.group(1)}_{m.group(2)}', camel)
# Insert an underscore between a lowercase letter and an uppercase letter
snake = re.sub(r'([a-z])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
# Insert an underscore between a digit and an uppercase letter
snake = re.sub(r'([0-9])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
# Insert an underscore between a lowercase letter and a digit
snake = re.sub(r'([a-z])([0-9])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
return snake.lower()
1 change: 1 addition & 0 deletions tests/test_utils.py
Expand Up @@ -529,6 +529,7 @@ def test_snake2camel(value: str, result: str) -> None:
('Camel2Snake', 'camel_2_snake'),
('_CamelToSnake', '_camel_to_snake'),
('CamelToSnake_', 'camel_to_snake_'),
('CAMELToSnake', 'camel_to_snake'),
('__CamelToSnake__', '__camel_to_snake__'),
('Camel2', 'camel_2'),
('Camel2_', 'camel_2_'),
Expand Down