Skip to content

pydantic.alias_generators

Alias generators for converting between different capitalization conventions.

to_camel

to_camel(snake)

Convert a snake_case string to camelCase.

Parameters:

Name Type Description Default
snake str

The string to convert.

required

Returns:

Type Description
str

The converted camelCase string.

Source code in pydantic/alias_generators.py
20
21
22
23
24
25
26
27
28
29
30
def to_camel(snake: str) -> str:
    """Convert a snake_case string to camelCase.

    Args:
        snake: The string to convert.

    Returns:
        The converted camelCase string.
    """
    camel = to_pascal(snake)
    return re.sub('(^_*[A-Z])', lambda m: m.group(1).lower(), camel)

to_pascal

to_pascal(snake)

Convert a snake_case string to PascalCase.

Parameters:

Name Type Description Default
snake str

The string to convert.

required

Returns:

Type Description
str

The PascalCase string.

Source code in pydantic/alias_generators.py
 7
 8
 9
10
11
12
13
14
15
16
17
def to_pascal(snake: str) -> str:
    """Convert a snake_case string to PascalCase.

    Args:
        snake: The string to convert.

    Returns:
        The PascalCase string.
    """
    camel = snake.title()
    return re.sub('([0-9A-Za-z])_(?=[0-9A-Z])', lambda m: m.group(1), camel)

to_snake

to_snake(camel)

Convert a PascalCase or camelCase string to snake_case.

Parameters:

Name Type Description Default
camel str

The string to convert.

required

Returns:

Type Description
str

The converted string in snake_case.

Source code in pydantic/alias_generators.py
33
34
35
36
37
38
39
40
41
42
43
44
def to_snake(camel: str) -> str:
    """Convert a PascalCase or camelCase string to snake_case.

    Args:
        camel: The string to convert.

    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)
    return snake.lower()