def pluralized(word, count, include_number=False): '''Pluralize the "word" if "count" is > 1 or has length > 1. If "include_number" is true, then the value of "count" will be prepended before the string: files_list = ['one.txt', 'two.txt', 'three.txt'] plural('file', files_list) --> 'files' plural('file', files_list, True) --> '3 files' This function is useful in f-strings when words refer to a number of items whose total or length is only known at run time. For example, f"Uploading {pluralized('file', files_list, True)} to server." ''' if isinstance(count, int): num = count elif isinstance(count, (list, set, dict)) or type(count) is {}.values().__class__: num = len(count) else: # If we can't figure out what kind of thing we're counting, we can't # pluralize, so just return the word as-is. return word text = pluralize(word) if (num > 1 or num == 0) else word if include_number: # Humanize imports pkg_resources, which takes a long time to load. # Delay loading it so that application startup times can be faster. from humanize import intcomma return f'{intcomma(num)} {text}' else: return text
def get_cardinalized_args_label(name, min_count, max_count): ''' Examples for parameter values: (min_count, max_count): output for name=arg: 1, 1: arg 0, 1: [arg] 0, None: [args ...] 1, 3: args ... ''' if min_count == max_count: return ' '.join([name] * min_count) if min_count == 1: return name + ' ' + get_cardinalized_args_label(name, min_count=0, max_count=max_count - 1 if max_count is not None else None) tmpl = '[%s]' if min_count == 0 else '%s' if max_count == 1: return tmpl % name return tmpl % (pluralize(name) + ' ...')