Debian Codegraph @

cloup/_util.py

raw
1 """Generic utilities."""
2 import importlib.metadata
3 from typing import (
4 Any, Dict, Hashable, Iterable, List, Optional, Sequence, Type, TypeVar,
5 )
6
7 from cloup.typing import MISSING, Possibly
8
9 click_version_tuple = tuple(importlib.metadata.version("click").split('.'))
10 click_major = int(click_version_tuple[0])
11 click_minor = int(click_version_tuple[1])
12 click_version_ge_8_1 = (click_major, click_minor) >= (8, 1)
13 click_version_ge_8_2 = (click_major, click_minor) >= (8, 2)
14
15 T = TypeVar('T')
16 K = TypeVar('K', bound=Hashable)
17 V = TypeVar('V')
18
19
20 def pick_non_missing(d: Dict[K, Possibly[V]]) -> Dict[K, V]:
21 return {key: val for key, val in d.items() if val is not MISSING}
22
23
24 def class_name(obj: object) -> str:
25 return obj.__class__.__name__
26
27
28 def check_arg(condition: bool, msg: str = '') -> None:
29 if not condition:
30 raise ValueError(msg)
31
32
33 def indent_lines(lines: Iterable[str], width: int = 2) -> List[str]:
34 spaces = ' ' * width
35 return [spaces + line for line in lines]
36
37
38 def make_repr(
39 obj: Any,
40 *args: Any,
41 _line_len: int = 60,
42 _indent: int = 2,
43 **kwargs: Any
44 ) -> str:
45 """
46 Generate repr(obj).
47
48 :param obj:
49 object to represent
50 :param args:
51 positional arguments in the repr
52 :param _line_len:
53 if the repr length exceeds this, arguments will be on their own line;
54 if negative, the repr will be in a single line regardless of its length
55 :param _indent:
56 indentation width of arguments in case they are shown in their own line
57 :param kwargs:
58 keyword arguments in the repr
59 :return: str
60 """
61 cls_name = obj.__class__.__name__
62 arglist = [
63 *(repr(arg) for arg in args),
64 *(f'{key}={value!r}' for key, value in kwargs.items()),
65 ]
66 len_arglist = sum(len(s) for s in arglist)
67 total_len = len(cls_name) + len_arglist + 2 * len(arglist)
68 if 0 <= _line_len < total_len:
69 lines = indent_lines(arglist, width=_indent)
70 args_text = ',\n'.join(lines)
71 return f'{cls_name}(\n{args_text}\n)'
72 else:
73 args_text = ', '.join(arglist)
74 return f'{cls_name}({args_text})'
75
76
77 def make_one_line_repr(obj: object, *args: Any, **kwargs: Any) -> str:
78 return make_repr(obj, *args, _line_len=-1, **kwargs)
79
80
81 def pluralize(
82 count: int, zero: str = '', one: str = '', many: str = '',
83 ) -> str:
84 if count == 0 and zero:
85 return zero
86 if count == 1 and one:
87 return one
88 return many.format(count=count)
89
90
91 def coalesce(*values: Optional[T]) -> Optional[T]:
92 """Return the first value that is not ``None``
93 (or ``None`` if no such value exists)."""
94 return next((val for val in values if val is not None), None)
95
96
97 def first_bool(*values: Any) -> bool:
98 """Return the first bool (or raises ``StopIteration`` if no bool is found)."""
99 return next(val for val in values if isinstance(val, bool))
100
101
102 def pick_not_none(iterable: Iterable[Optional[T]]) -> List[T]:
103 return [x for x in iterable if x is not None]
104
105
106 def check_positive_int(value: Any, arg_name: str) -> None:
107 error_type: Optional[Type[Exception]] = None
108 if not isinstance(value, int):
109 error_type = TypeError
110 elif value <= 0:
111 error_type = ValueError
112 if error_type:
113 raise error_type(
114 f'argument `{arg_name}` should be a positive integer; it is {value!r}'
115 )
116
117
118 def identity(x: T) -> T:
119 return x
120
121
122 class FrozenSpaceMeta(type):
123 def __init__(cls, *args: Any):
124 super().__init__(*args)
125 d = {k: v for k, v in vars(cls).items() if not k.startswith('_')}
126 type.__setattr__(cls, '_dict', d)
127
128 def __setattr__(cls, key: str, value: Any) -> None:
129 if key.startswith("__"):
130 return super().__setattr__(key, value)
131 else:
132 raise Exception(
133 "you can't set attributes on this class; only special dunder attributes "
134 "(e.g. __annotations__) are allowed to be set for compatibility reasons."
135 )
136
137 def asdict(cls) -> Dict[str, Any]:
138 return cls._dict # type: ignore
139
140 def __contains__(cls, item: str) -> bool:
141 return item in cls.asdict()
142
143 def __getitem__(cls, item: str) -> Any:
144 return cls._dict[item] # type: ignore
145
146
147 class FrozenSpace(metaclass=FrozenSpaceMeta):
148 """A class used just as frozen namespace for constants."""
149
150 def __init__(self) -> None:
151 raise Exception(
152 "this class is just a namespace for constants, it's not instantiable.")
153
154
155 def delete_keys(d: Dict[Any, Any], keys: Sequence[str]) -> None:
156 for key in keys:
157 del d[key]
158
159
160 def reindent(text: str, indent: int = 0) -> str:
161 import textwrap as tw
162 if text.startswith('\n'):
163 text = text[1:]
164 text = tw.dedent(text)
165 if indent:
166 return tw.indent(text, ' ' * indent)
167 return text