Skip to content

Commit

Permalink
Fix to_snake conversion (#8316)
Browse files Browse the repository at this point in the history
Co-authored-by: Jebin <jsubedi@thezebra.com>
  • Loading branch information
jevins09 and Jebin committed Dec 7, 2023
1 parent 2ccf1c3 commit e6798c7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
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

0 comments on commit e6798c7

Please sign in to comment.