alias_generators.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """Alias generators for converting between different capitalization conventions."""
  2. import re
  3. __all__ = ('to_pascal', 'to_camel', 'to_snake')
  4. def to_pascal(snake: str) -> str:
  5. """Convert a snake_case string to PascalCase.
  6. Args:
  7. snake: The string to convert.
  8. Returns:
  9. The PascalCase string.
  10. """
  11. camel = snake.title()
  12. return re.sub('([0-9A-Za-z])_(?=[0-9A-Z])', lambda m: m.group(1), camel)
  13. def to_camel(snake: str) -> str:
  14. """Convert a snake_case string to camelCase.
  15. Args:
  16. snake: The string to convert.
  17. Returns:
  18. The converted camelCase string.
  19. """
  20. camel = to_pascal(snake)
  21. return re.sub('(^_*[A-Z])', lambda m: m.group(1).lower(), camel)
  22. def to_snake(camel: str) -> str:
  23. """Convert a PascalCase or camelCase string to snake_case.
  24. Args:
  25. camel: The string to convert.
  26. Returns:
  27. The converted string in snake_case.
  28. """
  29. snake = re.sub(r'([a-zA-Z])([0-9])', lambda m: f'{m.group(1)}_{m.group(2)}', camel)
  30. snake = re.sub(r'([a-z0-9])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake)
  31. return snake.lower()