Skip to content

Commit 5694da3

Browse files
misrasaurabh1codeflash-ai[bot]sydney-runkle
authored
⚡️ Speed up to_snake() by 27% in pydantic/alias_generators.py (#9747)
Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com> Co-authored-by: Sydney Runkle <[email protected]>
1 parent df7340d commit 5694da3

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

pydantic/alias_generators.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,13 @@ def to_snake(camel: str) -> str:
4949
Returns:
5050
The converted string in snake_case.
5151
"""
52-
snake = re.sub(r'([a-zA-Z])([0-9])', lambda m: f'{m.group(1)}_{m.group(2)}', camel)
53-
snake = re.sub(r'([a-z0-9])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
54-
snake = re.sub(r'([A-Z]+)([A-Z][a-z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
55-
# Replace hyphens with underscores to handle kebab-case
56-
snake = snake.replace('-', '_')
52+
# `(?<=[a-zA-Z])(?=[0-9])` matches the space between a letter and a digit
53+
# `(?<=[a-z0-9])(?=[A-Z])` matches the space between a lowercase letter / digit and uppercase letter
54+
# `(?<=[A-Z])(?=[A-Z][a-z])` matches the space between two uppercase letters when the latter is followed by a lowercase letter
55+
# `-` matches a hyphen in order to convert kebab case strings
56+
snake = re.sub(
57+
r'(?<=[a-zA-Z])(?=[0-9])|(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|-',
58+
'_',
59+
camel,
60+
)
5761
return snake.lower()

0 commit comments

Comments
 (0)