Add function to format a list human-readable

This commit is contained in:
2026-04-06 19:04:09 +02:00
parent 157c8712b2
commit bdf7cb4af7
3 changed files with 98 additions and 1 deletions
+50 -1
View File
@@ -19,6 +19,8 @@ The utilities for jcloud_docsgen
import pathlib
import os
import errno
from typing import Union
import types
class ExistingDirectory(pathlib.Path):
'''
@@ -33,4 +35,51 @@ class ExistingDirectory(pathlib.Path):
raise FileNotFoundError(errno.ENOENT, 'no such file or directory', path)
if not os.path.isdir(path):
raise NotADirectoryError(errno.ENOTDIR, 'not a directory', path)
super().__init__(*(path, *args), **kwargs)
super().__init__(*(path, *args), **kwargs)
def _quote(string: str, quotation_mark: str) -> str:
'''
Quotes a string.
:param string: The string to quote
:type string: str
:param quotation_mark: The quotation mark
:type quotation_mark: str
:return: The quoted string
:rtype: str
'''
return quotation_mark + string + quotation_mark
def human_readable_list(ls: list, final_separator: str = 'and', quotation_mark: str = '') -> str:
'''
Generates a human-readable list from a list.
:param ls: The list.
:type ls: list
:param final_separator: The seperator between the last and the
second-to-last element of the list. Default
is 'and'.
:type final_separator: str
:param quotation_mark: The characters that are inserted before and
after an element. Default is ''.
:return: The human-readable list.
:rtype: str
'''
# empty list
if not ls:
return ''
# list with one element
if len(ls) == 1:
return _quote(str(ls[0]), quotation_mark)
return ', '.join(
[
_quote(str(obj), quotation_mark) # quote the string representation of the object
for obj in ls[:-1] # do not include the last element of the list
]
) + ' ' + final_separator + ' ' + _quote(str(ls[-1]), quotation_mark)