generated from jCloud/repository-template
Add function to format a list human-readable
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user