Skip to content
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
18 changes: 18 additions & 0 deletions _python_utils_tests/test_formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,24 @@ def test_camel_to_underscore_keeps_acronyms_whole(
assert formatters.camel_to_underscore(name) == expected


@pytest.mark.parametrize(
('name', 'expected'),
[
('ABc', 'a_bc'),
('ABCd', 'ab_cd'),
('IPad', 'i_pad'),
('AName', 'a_name'),
('__ABc__', '__a_bc__'),
('XMLParser', 'xml_parser'),
],
)
def test_camel_to_underscore_splits_short_acronym_boundary(
name: str, expected: str
) -> None:
"""Keep the final capital with the word following even a short acronym."""
assert formatters.camel_to_underscore(name) == expected


def test_timesince_date_raises_type_error() -> None:
"""Keep raising ``TypeError`` for a date, which has no time."""
today: typing.Any = datetime.date.today()
Expand Down
11 changes: 6 additions & 5 deletions python_utils/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@ def camel_to_underscore(name: str) -> str:
# Uppercase and the previous character isn't upper/underscore?
# Add the underscore
output.append('_')
elif i > 3 and c.islower():
# Will return the last 3 letters to check if we are changing
# case. Only a lowercase letter ends an acronym, an underscore
# or a digit after it leaves the acronym whole.
previous = name[i - 3 : i]
elif i > 1 and c.islower():
# Two preceding capitals are enough to mark the boundary:
# the final capital belongs to the following word. Only a
# lowercase letter ends an acronym; an underscore or digit
# after it leaves the acronym whole.
previous = name[i - 2 : i]
if previous.isalpha() and previous.isupper():
output.insert(len(output) - 1, '_')

Expand Down
Loading