-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path_checks.py
More file actions
258 lines (222 loc) · 7.34 KB
/
Copy path_checks.py
File metadata and controls
258 lines (222 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""Utility functions for checking types and values. Inspired from MNE."""
from __future__ import annotations
import logging
import operator
import os
from pathlib import Path
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from typing import Any
def ensure_int(item: Any, item_name: str | None = None) -> int:
"""Ensure a variable is an integer.
Parameters
----------
item : Any
Item to check.
item_name : str | None
Name of the item to show inside the error message.
Returns
-------
item : int
Item validated and converted to a Python integer.
Raises
------
TypeError
When the type of the item is not int.
"""
# This is preferred over numbers.Integral, see:
# https://github.com/scipy/scipy/pull/7351#issuecomment-299713159
try:
# someone passing True/False is much more likely to be an error than
# intentional usage
if isinstance(item, bool):
raise TypeError
item = int(operator.index(item))
except TypeError as exc:
item_name = "Item" if item_name is None else f"'{item_name}'"
exc.add_note(f"{item_name} must be an integer, got {type(item)} instead.")
raise
return item
class _IntLike:
@classmethod
def __instancecheck__(cls, other: Any) -> bool:
try:
ensure_int(other)
except TypeError:
return False
else:
return True
class _Callable:
@classmethod
def __instancecheck__(cls, other: Any) -> bool:
return callable(other)
_types = {
"numeric": (np.floating, float, _IntLike()),
"path-like": (str, Path, os.PathLike),
"int-like": (_IntLike(),),
"callable": (_Callable(),),
"array-like": (list, tuple, set, np.ndarray),
}
def check_type(item: Any, types: tuple, item_name: str | None = None) -> None:
"""Check that item is an instance of types.
Parameters
----------
item : object
Item to check.
types : tuple of types | tuple of str
Types to be checked against.
If str, must be one of ('int-like', 'numeric', 'path-like', 'callable',
'array-like').
item_name : str | None
Name of the item to show inside the error message.
Raises
------
TypeError
When the type of the item is not one of the valid options.
"""
check_types = sum(
(
(type(None),)
if type_ is None
else (type_,)
if not isinstance(type_, str)
else _types[type_]
for type_ in types
),
(),
)
if not isinstance(item, check_types):
type_name = [
"None"
if cls_ is None
else cls_.__name__
if not isinstance(cls_, str)
else cls_
for cls_ in types
]
if len(type_name) == 1:
type_name = type_name[0]
elif len(type_name) == 2:
type_name = " or ".join(type_name)
else:
type_name[-1] = "or " + type_name[-1]
type_name = ", ".join(type_name)
item_name = "Item" if item_name is None else f"'{item_name}'"
raise TypeError(
f"{item_name} must be an instance of {type_name}, got {type(item)} instead."
)
def check_value(
item: Any,
allowed_values: tuple | dict[Any, Any],
item_name: str | None = None,
extra: str | None = None,
) -> None:
"""Check the value of a parameter against a list of valid options.
Parameters
----------
item : object
Item to check.
allowed_values : tuple of objects | dict of objects
Allowed values to be checked against. If a dictionary, checks against the keys.
item_name : str | None
Name of the item to show inside the error message.
extra : str | None
Extra string to append to the invalid value sentence, e.g. "when using DC mode".
Raises
------
ValueError
When the value of the item is not one of the valid options.
"""
if item not in allowed_values:
item_name = "" if item_name is None else f" '{item_name}'"
extra = "" if extra is None else " " + extra
msg = (
"Invalid value for the{item_name} parameter{extra}. "
"{options}, but got {item!r} instead."
)
allowed_values = tuple(allowed_values) # e.g., if a dict was given
if len(allowed_values) == 1:
options = f"The only allowed value is {repr(allowed_values[0])}"
elif len(allowed_values) == 2:
options = (
f"Allowed values are {repr(allowed_values[0])} "
f"and {repr(allowed_values[1])}"
)
else:
options = "Allowed values are "
options += ", ".join([f"{repr(v)}" for v in allowed_values[:-1]])
options += f", and {repr(allowed_values[-1])}"
raise ValueError(
msg.format(item_name=item_name, extra=extra, options=options, item=item)
)
def ensure_verbose(verbose: Any) -> int:
"""Ensure that the value of verbose is valid.
Parameters
----------
verbose : int | str | bool | None
Sets the verbosity level. The verbosity increases gradually between
``"CRITICAL"``, ``"ERROR"``, ``"WARNING"``, ``"INFO"`` and ``"DEBUG"``. If
``None`` is provided, the verbosity is set to ``"WARNING"``. If a bool is
provided, the verbosity is set to ``"WARNING"`` for ``False`` and to ``"INFO"``
for ``True``.
Returns
-------
verbose : int
The verbosity level as an integer.
"""
logging_types = dict(
DEBUG=logging.DEBUG,
INFO=logging.INFO,
WARNING=logging.WARNING,
ERROR=logging.ERROR,
CRITICAL=logging.CRITICAL,
)
check_type(verbose, (bool, str, "int-like", None), item_name="verbose")
if verbose is None:
verbose = logging.WARNING
elif isinstance(verbose, str):
verbose = verbose.upper()
check_value(verbose, logging_types, item_name="verbose")
verbose = logging_types[verbose]
elif isinstance(verbose, bool):
if verbose:
verbose = logging.INFO
else:
verbose = logging.WARNING
elif isinstance(verbose, int):
verbose = ensure_int(verbose)
if verbose <= 0:
raise ValueError(
f"Argument 'verbose' can not be a negative integer, {verbose} is "
"invalid."
)
return verbose
def ensure_path(item: Any, must_exist: bool) -> Path:
"""Ensure a variable is a Path.
Parameters
----------
item : Any
Item to check.
must_exist : bool
If True, the path must resolve to an existing file or directory.
Returns
-------
path : Path
Path validated and converted to a pathlib.Path object.
"""
try:
item = Path(item)
except TypeError as exc:
try:
str_ = f"'{str(item)}' "
except Exception:
str_ = ""
exc.add_note(
f"The provided path {str_}is invalid and can not be converted. Please "
f"provide a str, an os.PathLike or a pathlib.Path object, not {type(item)}."
)
raise
if must_exist and not item.exists():
raise FileNotFoundError(f"The provided path '{str(item)}' does not exist.")
return item