Skip to content

Commit 5f1fc97

Browse files
committed
add a utility function for building nice messages from lists of strings
Signed-off-by: Doug Hellmann <[email protected]>
1 parent a16f622 commit 5f1fc97

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/pip/_internal/utils/messages.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""
2+
Utility functions for building messages.
3+
"""
4+
5+
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
6+
7+
if MYPY_CHECK_RUNNING:
8+
from typing import List
9+
10+
11+
def oxford_comma_join(
12+
values, # type: List[str]
13+
conjunction='and', # type: str
14+
):
15+
# type: (...) -> str
16+
"Join a list of strings for output in a message."
17+
if not values:
18+
return ''
19+
if len(values) == 1:
20+
return values[0]
21+
comma = ''
22+
if len(values) > 2:
23+
comma = ','
24+
return '{}{} {} {}'.format(
25+
', '.join(values[:-1]),
26+
comma,
27+
conjunction,
28+
values[-1],
29+
)

tests/unit/test_messages.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""Tests for pip._internal.messages
2+
"""
3+
4+
from pip._internal.utils.messages import oxford_comma_join
5+
6+
7+
def test_empty_list():
8+
assert '' == oxford_comma_join([])
9+
10+
11+
def test_one_item():
12+
assert 'a' == oxford_comma_join(['a'])
13+
14+
15+
def test_two_items():
16+
assert 'a and b' == oxford_comma_join(['a', 'b'])
17+
18+
19+
def test_three_items():
20+
assert 'a, b, and c' == oxford_comma_join(['a', 'b', 'c'])
21+
22+
23+
def test_two_items_or():
24+
assert 'a or b' == oxford_comma_join(['a', 'b'], 'or')

0 commit comments

Comments
 (0)