Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

optionally treat digits as capitals when converting to snake case #417

Merged
merged 3 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions camel_converter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,26 @@ def to_camel(snake_string: str) -> str:


@lru_cache(maxsize=4096)
def to_snake(camel_string: str) -> str:
def to_snake(camel_string: str, *, treat_digits_as_capitals: bool = False) -> str:
"""Converts a camel case or pascal case string to snake case.

Args:
camel_string: String in camel case or pascal case format. For example myVariable.
camel_string:
String in camel case or pascal case format. For example myVariable.
treat_digits_as_capitals:
Whether to treat digits as capitals. For example myVariable2 would become my_variable_2 rather than my_variable2.

Returns:
The string in snake case format. For example my_variable.
"""
return "".join([f"_{c}" if c.isupper() else c for c in camel_string]).lstrip("_").lower()

def check_character(c: str) -> str:
if c.isupper() or (treat_digits_as_capitals and c.isdigit()):
return f"_{c}"
else:
return c

return "".join([check_character(c) for c in camel_string]).lstrip("_").lower()


@lru_cache(maxsize=4096)
Expand Down
14 changes: 8 additions & 6 deletions tests/test_camel_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,12 +146,14 @@ def test_to_pascal(test_str, expected_str):


@pytest.mark.parametrize(
"test_str, expected_str",
"test_str, expected_str, treat_digits_as_capitals",
[
("thisIsATest", "this_is_a_test"),
("ThisIsATest", "this_is_a_test"),
("aTestWith12Number", "a_test_with12_number"),
("thisIsATest", "this_is_a_test", False),
("ThisIsATest", "this_is_a_test", False),
("aTestWith12Number", "a_test_with12_number", False),
("aTestWith12Number", "a_test_with_1_2_number", True),
("ATestWith12Number", "a_test_with_1_2_number", True),
],
)
def test_to_snake(test_str, expected_str):
assert to_snake(test_str) == expected_str
def test_to_snake(test_str, expected_str, treat_digits_as_capitals):
assert to_snake(test_str, treat_digits_as_capitals=treat_digits_as_capitals) == expected_str