Skip to content

Commit

Permalink
allow fmt argument of conjoin to be a function.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ken Kundert authored and Ken Kundert committed May 26, 2020
1 parent 20107aa commit 90ac5fd
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
1 change: 1 addition & 0 deletions doc/releases.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Releases
- Allow :class:`inform.ProgressBar` output to be suppressed.
- Allow ``/`` to be overridden in :class:`inform.plural`
- Various enhancements to :func:`inform.conjoin` and :func:`inform.full_stop`.

**1.20 (2020-01-08)**:
- Add *format* method to :class:`inform.plural`.
Expand Down
15 changes: 13 additions & 2 deletions inform/inform.py
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,9 @@ def conjoin(iterable, conj=' and ', sep=', ', end='', fmt=None):
Is added to the end of the returned string.
fmt (string):
A format string used to convert each item in *iterable* to a string.
If not given, str() is used.
May be a function, in which case it called on each member of
*iterable* and must return a string.
If *fmt* is not given, str() is used.
Return the items of the *iterable* joined into a string, where *conj* is
used to join the last two items in the list, and *sep* is used to join the
Expand Down Expand Up @@ -831,9 +833,18 @@ def conjoin(iterable, conj=' and ', sep=', ', end='', fmt=None):
carol : <carol@btca.com>; &
alice : <alice@btca.com>.
>>> display(conjoin(characters, fmt=lambda a: f'{a.name:>7} : <{a.email}>', conj='\n', sep='\n'))
bob : <bob@btca.com>
ted : <ted@btca.com>
carol : <carol@btca.com>
alice : <alice@btca.com>
"""
if fmt:
lst = [fmt.format(m) for m in iterable]
if callable(fmt):
lst = [fmt(m) for m in iterable]
else:
lst = [fmt.format(m) for m in iterable]
else:
lst = [str(m) for m in iterable]
if conj and len(lst) > 1:
Expand Down
7 changes: 6 additions & 1 deletion tests/test_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,12 @@ def test_conjoin():
alice : <alice@btca.com>.
''').strip()


assert conjoin(characters, fmt=lambda a: a.render('{name} : <{email}>'), conj='\n', sep='\n') == dedent('''
bob : <bob@btca.com>
ted : <ted@btca.com>
carol : <carol@btca.com>
alice : <alice@btca.com>
''').strip()

def test_did_you_mean():
assert did_you_mean('abc', ['bcd']) == 'bcd'
Expand Down

0 comments on commit 90ac5fd

Please sign in to comment.