utils.pyi 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. import ast
  2. import sys
  3. import types
  4. import unittest
  5. import warnings
  6. from _typeshed import ConvertibleToFloat, GenericPath, StrOrBytesPath, StrPath
  7. from collections.abc import Callable, Iterable, Sequence
  8. from contextlib import _GeneratorContextManager
  9. from pathlib import Path
  10. from re import Pattern
  11. from typing import (
  12. Any,
  13. AnyStr,
  14. ClassVar,
  15. Final,
  16. Generic,
  17. Literal as L,
  18. NoReturn,
  19. ParamSpec,
  20. Self,
  21. SupportsIndex,
  22. TypeAlias,
  23. TypeVarTuple,
  24. overload,
  25. type_check_only,
  26. )
  27. from typing_extensions import TypeVar, deprecated
  28. from unittest.case import SkipTest
  29. import numpy as np
  30. from numpy._typing import (
  31. ArrayLike,
  32. DTypeLike,
  33. NDArray,
  34. _ArrayLikeDT64_co,
  35. _ArrayLikeNumber_co,
  36. _ArrayLikeObject_co,
  37. _ArrayLikeTD64_co,
  38. )
  39. __all__ = [ # noqa: RUF022
  40. "IS_EDITABLE",
  41. "IS_MUSL",
  42. "IS_PYPY",
  43. "IS_PYSTON",
  44. "IS_WASM",
  45. "IS_INSTALLED",
  46. "IS_64BIT",
  47. "HAS_LAPACK64",
  48. "HAS_REFCOUNT",
  49. "BLAS_SUPPORTS_FPE",
  50. "NOGIL_BUILD",
  51. "NUMPY_ROOT",
  52. "assert_",
  53. "assert_array_almost_equal_nulp",
  54. "assert_raises_regex",
  55. "assert_array_max_ulp",
  56. "assert_warns",
  57. "assert_no_warnings",
  58. "assert_allclose",
  59. "assert_equal",
  60. "assert_almost_equal",
  61. "assert_approx_equal",
  62. "assert_array_equal",
  63. "assert_array_less",
  64. "assert_string_equal",
  65. "assert_array_almost_equal",
  66. "assert_raises",
  67. "build_err_msg",
  68. "decorate_methods",
  69. "jiffies",
  70. "memusage",
  71. "print_assert_equal",
  72. "rundocs",
  73. "runstring",
  74. "verbose",
  75. "measure",
  76. "IgnoreException",
  77. "clear_and_catch_warnings",
  78. "SkipTest",
  79. "KnownFailureException",
  80. "temppath",
  81. "tempdir",
  82. "suppress_warnings",
  83. "assert_array_compare",
  84. "assert_no_gc_cycles",
  85. "break_cycles",
  86. "check_support_sve",
  87. "run_threaded",
  88. ]
  89. ###
  90. _T = TypeVar("_T")
  91. _Ts = TypeVarTuple("_Ts")
  92. _Tss = ParamSpec("_Tss")
  93. _ET = TypeVar("_ET", bound=BaseException, default=BaseException)
  94. _FT = TypeVar("_FT", bound=Callable[..., Any])
  95. _W_co = TypeVar("_W_co", bound=_WarnLog | None, default=_WarnLog | None, covariant=True)
  96. _StrLike: TypeAlias = str | bytes
  97. _RegexLike: TypeAlias = _StrLike | Pattern[Any]
  98. _NumericArrayLike: TypeAlias = _ArrayLikeNumber_co | _ArrayLikeObject_co
  99. _ExceptionSpec: TypeAlias = type[_ET] | tuple[type[_ET], ...]
  100. _WarningSpec: TypeAlias = type[Warning]
  101. _WarnLog: TypeAlias = list[warnings.WarningMessage]
  102. _ToModules: TypeAlias = Iterable[types.ModuleType]
  103. # Must return a bool or an ndarray/generic type that is supported by `np.logical_and.reduce`
  104. _ComparisonFunc: TypeAlias = Callable[
  105. [NDArray[Any], NDArray[Any]],
  106. bool | np.bool | np.number | NDArray[np.bool | np.number | np.object_],
  107. ]
  108. # Type-check only `clear_and_catch_warnings` subclasses for both values of the
  109. # `record` parameter. Copied from the stdlib `warnings` stubs.
  110. @type_check_only
  111. class _clear_and_catch_warnings_with_records(clear_and_catch_warnings):
  112. def __enter__(self) -> list[warnings.WarningMessage]: ...
  113. @type_check_only
  114. class _clear_and_catch_warnings_without_records(clear_and_catch_warnings):
  115. def __enter__(self) -> None: ...
  116. ###
  117. verbose: int = 0
  118. NUMPY_ROOT: Final[Path] = ...
  119. IS_INSTALLED: Final[bool] = ...
  120. IS_EDITABLE: Final[bool] = ...
  121. IS_MUSL: Final[bool] = ...
  122. IS_PYPY: Final[bool] = ...
  123. IS_PYSTON: Final[bool] = ...
  124. IS_WASM: Final[bool] = ...
  125. IS_64BIT: Final[bool] = ...
  126. HAS_REFCOUNT: Final[bool] = ...
  127. HAS_LAPACK64: Final[bool] = ...
  128. BLAS_SUPPORTS_FPE: Final[bool] = ...
  129. NOGIL_BUILD: Final[bool] = ...
  130. class KnownFailureException(Exception): ...
  131. class IgnoreException(Exception): ...
  132. class clear_and_catch_warnings(warnings.catch_warnings[_W_co], Generic[_W_co]):
  133. class_modules: ClassVar[tuple[types.ModuleType, ...]] = ()
  134. modules: Final[set[types.ModuleType]]
  135. @overload # record: True
  136. def __init__(self: clear_and_catch_warnings[_WarnLog], /, record: L[True], modules: _ToModules = ()) -> None: ...
  137. @overload # record: False (default)
  138. def __init__(self: clear_and_catch_warnings[None], /, record: L[False] = False, modules: _ToModules = ()) -> None: ...
  139. @overload # record; bool
  140. def __init__(self, /, record: bool, modules: _ToModules = ()) -> None: ...
  141. @deprecated("Please use warnings.filterwarnings or pytest.mark.filterwarnings instead")
  142. class suppress_warnings:
  143. log: Final[_WarnLog]
  144. def __init__(self, /, forwarding_rule: L["always", "module", "once", "location"] = "always") -> None: ...
  145. def __enter__(self) -> Self: ...
  146. def __exit__(self, cls: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None, /) -> None: ...
  147. def __call__(self, /, func: _FT) -> _FT: ...
  148. #
  149. def filter(self, /, category: type[Warning] = ..., message: str = "", module: types.ModuleType | None = None) -> None: ...
  150. def record(self, /, category: type[Warning] = ..., message: str = "", module: types.ModuleType | None = None) -> _WarnLog: ...
  151. # Contrary to runtime we can't do `os.name` checks while type checking,
  152. # only `sys.platform` checks
  153. if sys.platform == "win32" or sys.platform == "cygwin":
  154. def memusage(processName: str = "python", instance: int = 0) -> int: ...
  155. elif sys.platform == "linux":
  156. def memusage(_proc_pid_stat: StrOrBytesPath | None = None) -> int | None: ...
  157. else:
  158. def memusage() -> NoReturn: ...
  159. if sys.platform == "linux":
  160. def jiffies(_proc_pid_stat: StrOrBytesPath | None = None, _load_time: list[float] | None = None) -> int: ...
  161. else:
  162. def jiffies(_load_time: list[float] = []) -> int: ...
  163. #
  164. def build_err_msg(
  165. arrays: Iterable[object],
  166. err_msg: object,
  167. header: str = "Items are not equal:",
  168. verbose: bool = True,
  169. names: Sequence[str] = ("ACTUAL", "DESIRED"), # = ('ACTUAL', 'DESIRED')
  170. precision: SupportsIndex | None = 8,
  171. ) -> str: ...
  172. #
  173. def print_assert_equal(test_string: str, actual: object, desired: object) -> None: ...
  174. #
  175. def assert_(val: object, msg: str | Callable[[], str] = "") -> None: ...
  176. #
  177. def assert_equal(
  178. actual: object,
  179. desired: object,
  180. err_msg: object = "",
  181. verbose: bool = True,
  182. *,
  183. strict: bool = False,
  184. ) -> None: ...
  185. def assert_almost_equal(
  186. actual: _NumericArrayLike,
  187. desired: _NumericArrayLike,
  188. decimal: int = 7,
  189. err_msg: object = "",
  190. verbose: bool = True,
  191. ) -> None: ...
  192. #
  193. def assert_approx_equal(
  194. actual: ConvertibleToFloat,
  195. desired: ConvertibleToFloat,
  196. significant: int = 7,
  197. err_msg: object = "",
  198. verbose: bool = True,
  199. ) -> None: ...
  200. #
  201. def assert_array_compare(
  202. comparison: _ComparisonFunc,
  203. x: ArrayLike,
  204. y: ArrayLike,
  205. err_msg: object = "",
  206. verbose: bool = True,
  207. header: str = "",
  208. precision: SupportsIndex = 6,
  209. equal_nan: bool = True,
  210. equal_inf: bool = True,
  211. *,
  212. strict: bool = False,
  213. names: tuple[str, str] = ("ACTUAL", "DESIRED"),
  214. ) -> None: ...
  215. #
  216. def assert_array_equal(
  217. actual: object,
  218. desired: object,
  219. err_msg: object = "",
  220. verbose: bool = True,
  221. *,
  222. strict: bool = False,
  223. ) -> None: ...
  224. #
  225. def assert_array_almost_equal(
  226. actual: _NumericArrayLike,
  227. desired: _NumericArrayLike,
  228. decimal: float = 6,
  229. err_msg: object = "",
  230. verbose: bool = True,
  231. ) -> None: ...
  232. @overload
  233. def assert_array_less(
  234. x: _ArrayLikeDT64_co,
  235. y: _ArrayLikeDT64_co,
  236. err_msg: object = "",
  237. verbose: bool = True,
  238. *,
  239. strict: bool = False,
  240. ) -> None: ...
  241. @overload
  242. def assert_array_less(
  243. x: _ArrayLikeTD64_co,
  244. y: _ArrayLikeTD64_co,
  245. err_msg: object = "",
  246. verbose: bool = True,
  247. *,
  248. strict: bool = False,
  249. ) -> None: ...
  250. @overload
  251. def assert_array_less(
  252. x: _NumericArrayLike,
  253. y: _NumericArrayLike,
  254. err_msg: object = "",
  255. verbose: bool = True,
  256. *,
  257. strict: bool = False,
  258. ) -> None: ...
  259. #
  260. def assert_string_equal(actual: str, desired: str) -> None: ...
  261. #
  262. @overload
  263. def assert_raises(
  264. exception_class: _ExceptionSpec[_ET],
  265. /,
  266. *,
  267. msg: str | None = None,
  268. ) -> unittest.case._AssertRaisesContext[_ET]: ...
  269. @overload
  270. def assert_raises(
  271. exception_class: _ExceptionSpec,
  272. callable: Callable[_Tss, Any],
  273. /,
  274. *args: _Tss.args,
  275. **kwargs: _Tss.kwargs,
  276. ) -> None: ...
  277. #
  278. @overload
  279. def assert_raises_regex(
  280. exception_class: _ExceptionSpec[_ET],
  281. expected_regexp: _RegexLike,
  282. *,
  283. msg: str | None = None,
  284. ) -> unittest.case._AssertRaisesContext[_ET]: ...
  285. @overload
  286. def assert_raises_regex(
  287. exception_class: _ExceptionSpec,
  288. expected_regexp: _RegexLike,
  289. callable: Callable[_Tss, Any],
  290. *args: _Tss.args,
  291. **kwargs: _Tss.kwargs,
  292. ) -> None: ...
  293. #
  294. @overload
  295. def assert_allclose(
  296. actual: _ArrayLikeTD64_co,
  297. desired: _ArrayLikeTD64_co,
  298. rtol: float = 1e-7,
  299. atol: float = 0,
  300. equal_nan: bool = True,
  301. err_msg: object = "",
  302. verbose: bool = True,
  303. *,
  304. strict: bool = False,
  305. ) -> None: ...
  306. @overload
  307. def assert_allclose(
  308. actual: _NumericArrayLike,
  309. desired: _NumericArrayLike,
  310. rtol: float = 1e-7,
  311. atol: float = 0,
  312. equal_nan: bool = True,
  313. err_msg: object = "",
  314. verbose: bool = True,
  315. *,
  316. strict: bool = False,
  317. ) -> None: ...
  318. #
  319. def assert_array_almost_equal_nulp(
  320. x: _ArrayLikeNumber_co,
  321. y: _ArrayLikeNumber_co,
  322. nulp: float = 1,
  323. ) -> None: ...
  324. #
  325. def assert_array_max_ulp(
  326. a: _ArrayLikeNumber_co,
  327. b: _ArrayLikeNumber_co,
  328. maxulp: float = 1,
  329. dtype: DTypeLike | None = None,
  330. ) -> NDArray[Any]: ...
  331. #
  332. @overload
  333. @deprecated("Please use warnings.catch_warnings or pytest.warns instead")
  334. def assert_warns(warning_class: _WarningSpec) -> _GeneratorContextManager[None]: ...
  335. @overload
  336. @deprecated("Please use warnings.catch_warnings or pytest.warns instead")
  337. def assert_warns(warning_class: _WarningSpec, func: Callable[_Tss, _T], *args: _Tss.args, **kwargs: _Tss.kwargs) -> _T: ...
  338. #
  339. @overload
  340. def assert_no_warnings() -> _GeneratorContextManager[None]: ...
  341. @overload
  342. def assert_no_warnings(func: Callable[_Tss, _T], /, *args: _Tss.args, **kwargs: _Tss.kwargs) -> _T: ...
  343. #
  344. @overload
  345. def assert_no_gc_cycles() -> _GeneratorContextManager[None]: ...
  346. @overload
  347. def assert_no_gc_cycles(func: Callable[_Tss, Any], /, *args: _Tss.args, **kwargs: _Tss.kwargs) -> None: ...
  348. ###
  349. #
  350. @overload
  351. def tempdir(
  352. suffix: None = None,
  353. prefix: None = None,
  354. dir: None = None,
  355. ) -> _GeneratorContextManager[str]: ...
  356. @overload
  357. def tempdir(
  358. suffix: AnyStr | None = None,
  359. prefix: AnyStr | None = None,
  360. *,
  361. dir: GenericPath[AnyStr],
  362. ) -> _GeneratorContextManager[AnyStr]: ...
  363. @overload
  364. def tempdir(
  365. suffix: AnyStr | None = None,
  366. *,
  367. prefix: AnyStr,
  368. dir: GenericPath[AnyStr] | None = None,
  369. ) -> _GeneratorContextManager[AnyStr]: ...
  370. @overload
  371. def tempdir(
  372. suffix: AnyStr,
  373. prefix: AnyStr | None = None,
  374. dir: GenericPath[AnyStr] | None = None,
  375. ) -> _GeneratorContextManager[AnyStr]: ...
  376. #
  377. @overload
  378. def temppath(
  379. suffix: None = None,
  380. prefix: None = None,
  381. dir: None = None,
  382. text: bool = False,
  383. ) -> _GeneratorContextManager[str]: ...
  384. @overload
  385. def temppath(
  386. suffix: AnyStr | None,
  387. prefix: AnyStr | None,
  388. dir: GenericPath[AnyStr],
  389. text: bool = False,
  390. ) -> _GeneratorContextManager[AnyStr]: ...
  391. @overload
  392. def temppath(
  393. suffix: AnyStr | None = None,
  394. prefix: AnyStr | None = None,
  395. *,
  396. dir: GenericPath[AnyStr],
  397. text: bool = False,
  398. ) -> _GeneratorContextManager[AnyStr]: ...
  399. @overload
  400. def temppath(
  401. suffix: AnyStr | None,
  402. prefix: AnyStr,
  403. dir: GenericPath[AnyStr] | None = None,
  404. text: bool = False,
  405. ) -> _GeneratorContextManager[AnyStr]: ...
  406. @overload
  407. def temppath(
  408. suffix: AnyStr | None = None,
  409. *,
  410. prefix: AnyStr,
  411. dir: GenericPath[AnyStr] | None = None,
  412. text: bool = False,
  413. ) -> _GeneratorContextManager[AnyStr]: ...
  414. @overload
  415. def temppath(
  416. suffix: AnyStr,
  417. prefix: AnyStr | None = None,
  418. dir: GenericPath[AnyStr] | None = None,
  419. text: bool = False,
  420. ) -> _GeneratorContextManager[AnyStr]: ...
  421. #
  422. def check_support_sve(__cache: list[bool] = ..., /) -> bool: ... # stubdefaulter: ignore[missing-default]
  423. #
  424. def decorate_methods(
  425. cls: type,
  426. decorator: Callable[[Callable[..., Any]], Any],
  427. testmatch: _RegexLike | None = None,
  428. ) -> None: ...
  429. #
  430. @overload
  431. def run_threaded(
  432. func: Callable[[], None],
  433. max_workers: int = 8,
  434. pass_count: bool = False,
  435. pass_barrier: bool = False,
  436. outer_iterations: int = 1,
  437. prepare_args: None = None,
  438. ) -> None: ...
  439. @overload
  440. def run_threaded(
  441. func: Callable[[*_Ts], None],
  442. max_workers: int,
  443. pass_count: bool,
  444. pass_barrier: bool,
  445. outer_iterations: int,
  446. prepare_args: tuple[*_Ts],
  447. ) -> None: ...
  448. @overload
  449. def run_threaded(
  450. func: Callable[[*_Ts], None],
  451. max_workers: int = 8,
  452. pass_count: bool = False,
  453. pass_barrier: bool = False,
  454. outer_iterations: int = 1,
  455. *,
  456. prepare_args: tuple[*_Ts],
  457. ) -> None: ...
  458. #
  459. def runstring(astr: _StrLike | types.CodeType, dict: dict[str, Any] | None) -> Any: ... # noqa: ANN401
  460. def rundocs(filename: StrPath | None = None, raise_on_error: bool = True) -> None: ...
  461. def measure(code_str: _StrLike | ast.AST, times: int = 1, label: str | None = None) -> float: ...
  462. def break_cycles() -> None: ...