| 1 |
# uses code from https://github.com/daveoncode/python-string-utils |
| 2 |
|
| 3 |
import re |
| 4 |
|
| 5 |
__all__ = ["camel_to_snake", "snake_to_camel"] |
| 6 |
|
| 7 |
_re_camel_to_snake = re.compile(r"([a-z]|[A-Z0-9]+)(?=[A-Z])") |
| 8 |
_re_snake_to_camel = re.compile(r"(_)([a-z\d])") |
| 9 |
|
| 10 |
|
| 11 |
def camel_to_snake(s: str) -> str: |
| 12 |
"""Convert from CamelCase to snake_case""" |
| 13 |
return _re_camel_to_snake.sub(r"\1_", s).lower() |
| 14 |
|
| 15 |
|
| 16 |
def snake_to_camel(s: str, upper: bool = True) -> str: |
| 17 |
"""Convert from snake_case to CamelCase |
| 18 |
|
| 19 |
If upper is set, then convert to upper CamelCase, otherwise the first character |
| 20 |
keeps its case. |
| 21 |
""" |
| 22 |
s = _re_snake_to_camel.sub(lambda m: m.group(2).upper(), s) |
| 23 |
if upper: |
| 24 |
s = s[:1].upper() + s[1:] |
| 25 |
return s |