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

Support 'oxford comma' format and non-string types in listing #690

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
17 changes: 13 additions & 4 deletions src/human_readable/lists.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
"""Tests for lists humanization."""
from __future__ import annotations
from typing import TYPE_CHECKING


if TYPE_CHECKING:
from collections.abc import Sequence
from typing import Any


__all__ = ["listing"]


def listing(items: list[str], separator: str, conjunction: str = "") -> str:
def listing(items: Sequence[Any], separator: Any, conjunction: Any = None, oxford: bool = False) -> str:
"""Return human readable list separated by separator.

Optional argument is conjuntion that substitutes the last separator.
Expand All @@ -14,6 +20,7 @@ def listing(items: list[str], separator: str, conjunction: str = "") -> str:
items: list of items.
separator: separator of items.
conjunction: word/string as last separator. Defaults to None.
oxford: apply separators in the same manner as an oxford comma

Returns:
str: list in natural language.
Expand All @@ -22,11 +29,13 @@ def listing(items: list[str], separator: str, conjunction: str = "") -> str:
if len_items == 0:
return ""
if len_items == 1:
return items[0]
phrase = items[0]
if conjunction:
return str(items[0])
phrase = str(items[0])
if conjunction is not None:
for i in range(1, len_items - 1):
phrase += f"{separator} {items[i]}"
if oxford and len_items > 2:
phrase += str(separator)
phrase += f" {conjunction} {items[len_items - 1]}"
else:
for i in range(1, len_items):
Expand Down