numpy 2.5.2__cp315-cp315-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (942) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +108 -0
  3. numpy/__init__.cython-30.pxd +1312 -0
  4. numpy/__init__.pxd +12 -0
  5. numpy/__init__.py +926 -0
  6. numpy/__init__.pyi +7691 -0
  7. numpy/_array_api_info.py +349 -0
  8. numpy/_array_api_info.pyi +177 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +203 -0
  12. numpy/_core/__init__.pyi +666 -0
  13. numpy/_core/_add_newdocs.py +7131 -0
  14. numpy/_core/_add_newdocs.pyi +2 -0
  15. numpy/_core/_add_newdocs_scalars.py +381 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +130 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +54 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +48 -0
  25. numpy/_core/_internal.py +964 -0
  26. numpy/_core/_internal.pyi +56 -0
  27. numpy/_core/_methods.py +252 -0
  28. numpy/_core/_methods.pyi +22 -0
  29. numpy/_core/_multiarray_tests.cp315-win32.lib +0 -0
  30. numpy/_core/_multiarray_tests.cp315-win32.pyd +0 -0
  31. numpy/_core/_multiarray_umath.cp315-win32.lib +0 -0
  32. numpy/_core/_multiarray_umath.cp315-win32.pyd +0 -0
  33. numpy/_core/_operand_flag_tests.cp315-win32.lib +0 -0
  34. numpy/_core/_operand_flag_tests.cp315-win32.pyd +0 -0
  35. numpy/_core/_rational_tests.cp315-win32.lib +0 -0
  36. numpy/_core/_rational_tests.cp315-win32.pyd +0 -0
  37. numpy/_core/_simd.cp315-win32.lib +0 -0
  38. numpy/_core/_simd.cp315-win32.pyd +0 -0
  39. numpy/_core/_simd.pyi +35 -0
  40. numpy/_core/_string_helpers.py +100 -0
  41. numpy/_core/_string_helpers.pyi +12 -0
  42. numpy/_core/_struct_ufunc_tests.cp315-win32.lib +0 -0
  43. numpy/_core/_struct_ufunc_tests.cp315-win32.pyd +0 -0
  44. numpy/_core/_type_aliases.py +130 -0
  45. numpy/_core/_type_aliases.pyi +86 -0
  46. numpy/_core/_ufunc_config.py +515 -0
  47. numpy/_core/_ufunc_config.pyi +67 -0
  48. numpy/_core/_umath_tests.cp315-win32.lib +0 -0
  49. numpy/_core/_umath_tests.cp315-win32.pyd +0 -0
  50. numpy/_core/_umath_tests.pyi +51 -0
  51. numpy/_core/arrayprint.py +1788 -0
  52. numpy/_core/arrayprint.pyi +152 -0
  53. numpy/_core/cversions.py +13 -0
  54. numpy/_core/defchararray.py +1429 -0
  55. numpy/_core/defchararray.pyi +778 -0
  56. numpy/_core/einsumfunc.py +1647 -0
  57. numpy/_core/einsumfunc.pyi +179 -0
  58. numpy/_core/fromnumeric.py +4271 -0
  59. numpy/_core/fromnumeric.pyi +3144 -0
  60. numpy/_core/function_base.py +547 -0
  61. numpy/_core/function_base.pyi +444 -0
  62. numpy/_core/getlimits.py +449 -0
  63. numpy/_core/getlimits.pyi +124 -0
  64. numpy/_core/include/numpy/__multiarray_api.c +386 -0
  65. numpy/_core/include/numpy/__multiarray_api.h +1708 -0
  66. numpy/_core/include/numpy/__ufunc_api.c +56 -0
  67. numpy/_core/include/numpy/__ufunc_api.h +357 -0
  68. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  69. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  70. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  71. numpy/_core/include/numpy/arrayobject.h +7 -0
  72. numpy/_core/include/numpy/arrayscalars.h +228 -0
  73. numpy/_core/include/numpy/dtype_api.h +557 -0
  74. numpy/_core/include/numpy/halffloat.h +70 -0
  75. numpy/_core/include/numpy/ndarrayobject.h +288 -0
  76. numpy/_core/include/numpy/ndarraytypes.h +2075 -0
  77. numpy/_core/include/numpy/npy_2_compat.h +430 -0
  78. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  79. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  80. numpy/_core/include/numpy/npy_common.h +989 -0
  81. numpy/_core/include/numpy/npy_cpu.h +126 -0
  82. numpy/_core/include/numpy/npy_endian.h +79 -0
  83. numpy/_core/include/numpy/npy_math.h +602 -0
  84. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  85. numpy/_core/include/numpy/npy_os.h +42 -0
  86. numpy/_core/include/numpy/numpyconfig.h +187 -0
  87. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  88. numpy/_core/include/numpy/random/bitgen.h +20 -0
  89. numpy/_core/include/numpy/random/distributions.h +209 -0
  90. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  91. numpy/_core/include/numpy/ufuncobject.h +368 -0
  92. numpy/_core/include/numpy/utils.h +99 -0
  93. numpy/_core/lib/npymath.lib +0 -0
  94. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  95. numpy/_core/memmap.py +362 -0
  96. numpy/_core/memmap.pyi +94 -0
  97. numpy/_core/multiarray.py +1743 -0
  98. numpy/_core/multiarray.pyi +1892 -0
  99. numpy/_core/numeric.py +2707 -0
  100. numpy/_core/numeric.pyi +1366 -0
  101. numpy/_core/numerictypes.py +576 -0
  102. numpy/_core/numerictypes.pyi +196 -0
  103. numpy/_core/overrides.py +188 -0
  104. numpy/_core/overrides.pyi +44 -0
  105. numpy/_core/printoptions.py +32 -0
  106. numpy/_core/printoptions.pyi +28 -0
  107. numpy/_core/records.py +1089 -0
  108. numpy/_core/records.pyi +336 -0
  109. numpy/_core/shape_base.py +996 -0
  110. numpy/_core/shape_base.pyi +210 -0
  111. numpy/_core/strings.py +1813 -0
  112. numpy/_core/strings.pyi +481 -0
  113. numpy/_core/tests/_locales.py +72 -0
  114. numpy/_core/tests/_natype.py +144 -0
  115. numpy/_core/tests/data/astype_copy.pkl +0 -0
  116. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  117. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  118. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  119. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  123. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  125. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  127. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  128. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  129. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  131. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  132. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  133. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  135. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  136. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  137. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  138. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  139. numpy/_core/tests/examples/cython/checks.pyx +381 -0
  140. numpy/_core/tests/examples/cython/meson.build +52 -0
  141. numpy/_core/tests/examples/cython/setup.py +39 -0
  142. numpy/_core/tests/examples/limited_api/limited_api.c +455 -0
  143. numpy/_core/tests/examples/limited_api/limited_api_cython.pyx +155 -0
  144. numpy/_core/tests/examples/limited_api/meson.build +94 -0
  145. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  146. numpy/_core/tests/test__exceptions.py +90 -0
  147. numpy/_core/tests/test_abc.py +54 -0
  148. numpy/_core/tests/test_api.py +668 -0
  149. numpy/_core/tests/test_argparse.py +90 -0
  150. numpy/_core/tests/test_array_api_info.py +113 -0
  151. numpy/_core/tests/test_array_coercion.py +943 -0
  152. numpy/_core/tests/test_array_interface.py +222 -0
  153. numpy/_core/tests/test_arraymethod.py +85 -0
  154. numpy/_core/tests/test_arrayobject.py +198 -0
  155. numpy/_core/tests/test_arrayprint.py +1363 -0
  156. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  157. numpy/_core/tests/test_casting_unittests.py +970 -0
  158. numpy/_core/tests/test_conversion_utils.py +209 -0
  159. numpy/_core/tests/test_cpu_dispatcher.py +48 -0
  160. numpy/_core/tests/test_cpu_features.py +533 -0
  161. numpy/_core/tests/test_custom_dtypes.py +511 -0
  162. numpy/_core/tests/test_cython.py +377 -0
  163. numpy/_core/tests/test_datetime.py +3220 -0
  164. numpy/_core/tests/test_defchararray.py +879 -0
  165. numpy/_core/tests/test_deprecations.py +511 -0
  166. numpy/_core/tests/test_dlpack.py +262 -0
  167. numpy/_core/tests/test_dtype.py +2107 -0
  168. numpy/_core/tests/test_einsum.py +1368 -0
  169. numpy/_core/tests/test_errstate.py +131 -0
  170. numpy/_core/tests/test_extint128.py +217 -0
  171. numpy/_core/tests/test_finfo.py +86 -0
  172. numpy/_core/tests/test_function_base.py +502 -0
  173. numpy/_core/tests/test_getlimits.py +188 -0
  174. numpy/_core/tests/test_half.py +589 -0
  175. numpy/_core/tests/test_hashtable.py +156 -0
  176. numpy/_core/tests/test_indexerrors.py +122 -0
  177. numpy/_core/tests/test_indexing.py +1717 -0
  178. numpy/_core/tests/test_item_selection.py +178 -0
  179. numpy/_core/tests/test_limited_api.py +254 -0
  180. numpy/_core/tests/test_longdouble.py +370 -0
  181. numpy/_core/tests/test_mem_overlap.py +933 -0
  182. numpy/_core/tests/test_mem_policy.py +448 -0
  183. numpy/_core/tests/test_memmap.py +286 -0
  184. numpy/_core/tests/test_multiarray.py +11569 -0
  185. numpy/_core/tests/test_multiprocessing.py +55 -0
  186. numpy/_core/tests/test_multithreading.py +746 -0
  187. numpy/_core/tests/test_nditer.py +3690 -0
  188. numpy/_core/tests/test_nep50_promotions.py +287 -0
  189. numpy/_core/tests/test_numeric.py +4278 -0
  190. numpy/_core/tests/test_numerictypes.py +640 -0
  191. numpy/_core/tests/test_overrides.py +800 -0
  192. numpy/_core/tests/test_print.py +202 -0
  193. numpy/_core/tests/test_protocols.py +46 -0
  194. numpy/_core/tests/test_records.py +595 -0
  195. numpy/_core/tests/test_regression.py +2672 -0
  196. numpy/_core/tests/test_scalar_ctors.py +203 -0
  197. numpy/_core/tests/test_scalar_methods.py +327 -0
  198. numpy/_core/tests/test_scalarbuffer.py +154 -0
  199. numpy/_core/tests/test_scalarinherit.py +105 -0
  200. numpy/_core/tests/test_scalarmath.py +1167 -0
  201. numpy/_core/tests/test_scalarprint.py +403 -0
  202. numpy/_core/tests/test_shape_base.py +899 -0
  203. numpy/_core/tests/test_simd.py +1345 -0
  204. numpy/_core/tests/test_simd_module.py +105 -0
  205. numpy/_core/tests/test_stringdtype.py +2573 -0
  206. numpy/_core/tests/test_strings.py +1506 -0
  207. numpy/_core/tests/test_ufunc.py +3452 -0
  208. numpy/_core/tests/test_umath.py +5231 -0
  209. numpy/_core/tests/test_umath_accuracy.py +92 -0
  210. numpy/_core/tests/test_umath_complex.py +631 -0
  211. numpy/_core/tests/test_unicode.py +369 -0
  212. numpy/_core/umath.py +59 -0
  213. numpy/_core/umath.pyi +232 -0
  214. numpy/_distributor_init.py +15 -0
  215. numpy/_distributor_init.pyi +1 -0
  216. numpy/_expired_attrs_2_0.py +78 -0
  217. numpy/_expired_attrs_2_0.pyi +61 -0
  218. numpy/_globals.py +121 -0
  219. numpy/_globals.pyi +17 -0
  220. numpy/_pyinstaller/__init__.py +0 -0
  221. numpy/_pyinstaller/__init__.pyi +0 -0
  222. numpy/_pyinstaller/hook-numpy.py +35 -0
  223. numpy/_pyinstaller/hook-numpy.pyi +6 -0
  224. numpy/_pyinstaller/tests/__init__.py +16 -0
  225. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  226. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  227. numpy/_pytesttester.py +186 -0
  228. numpy/_pytesttester.pyi +18 -0
  229. numpy/_typing/__init__.py +147 -0
  230. numpy/_typing/_add_docstring.py +153 -0
  231. numpy/_typing/_array_like.py +92 -0
  232. numpy/_typing/_char_codes.py +156 -0
  233. numpy/_typing/_dtype_like.py +108 -0
  234. numpy/_typing/_extended_precision.py +15 -0
  235. numpy/_typing/_nbit.py +17 -0
  236. numpy/_typing/_nbit_base.py +93 -0
  237. numpy/_typing/_nbit_base.pyi +39 -0
  238. numpy/_typing/_nested_sequence.py +85 -0
  239. numpy/_typing/_scalars.py +20 -0
  240. numpy/_typing/_shape.py +8 -0
  241. numpy/_typing/_ufunc.py +7 -0
  242. numpy/_typing/_ufunc.pyi +970 -0
  243. numpy/_utils/__init__.py +95 -0
  244. numpy/_utils/__init__.pyi +25 -0
  245. numpy/_utils/_conversions.py +18 -0
  246. numpy/_utils/_conversions.pyi +4 -0
  247. numpy/_utils/_inspect.py +192 -0
  248. numpy/_utils/_inspect.pyi +67 -0
  249. numpy/_utils/_pep440.py +486 -0
  250. numpy/_utils/_pep440.pyi +121 -0
  251. numpy/char/__init__.py +31 -0
  252. numpy/char/__init__.pyi +111 -0
  253. numpy/conftest.py +249 -0
  254. numpy/core/__init__.py +33 -0
  255. numpy/core/__init__.pyi +45 -0
  256. numpy/core/_dtype.py +10 -0
  257. numpy/core/_dtype.pyi +0 -0
  258. numpy/core/_dtype_ctypes.py +10 -0
  259. numpy/core/_dtype_ctypes.pyi +0 -0
  260. numpy/core/_internal.py +27 -0
  261. numpy/core/_internal.pyi +1 -0
  262. numpy/core/_multiarray_umath.py +57 -0
  263. numpy/core/_utils.py +21 -0
  264. numpy/core/arrayprint.py +10 -0
  265. numpy/core/arrayprint.pyi +4 -0
  266. numpy/core/defchararray.py +10 -0
  267. numpy/core/defchararray.pyi +4 -0
  268. numpy/core/einsumfunc.py +10 -0
  269. numpy/core/einsumfunc.pyi +4 -0
  270. numpy/core/fromnumeric.py +10 -0
  271. numpy/core/fromnumeric.pyi +4 -0
  272. numpy/core/function_base.py +10 -0
  273. numpy/core/function_base.pyi +4 -0
  274. numpy/core/getlimits.py +10 -0
  275. numpy/core/getlimits.pyi +4 -0
  276. numpy/core/multiarray.py +25 -0
  277. numpy/core/multiarray.pyi +4 -0
  278. numpy/core/numeric.py +12 -0
  279. numpy/core/numeric.pyi +4 -0
  280. numpy/core/numerictypes.py +10 -0
  281. numpy/core/numerictypes.pyi +4 -0
  282. numpy/core/overrides.py +10 -0
  283. numpy/core/overrides.pyi +7 -0
  284. numpy/core/records.py +10 -0
  285. numpy/core/records.pyi +4 -0
  286. numpy/core/shape_base.py +10 -0
  287. numpy/core/shape_base.pyi +4 -0
  288. numpy/core/umath.py +10 -0
  289. numpy/core/umath.pyi +4 -0
  290. numpy/ctypeslib/__init__.py +13 -0
  291. numpy/ctypeslib/__init__.pyi +15 -0
  292. numpy/ctypeslib/_ctypeslib.py +603 -0
  293. numpy/ctypeslib/_ctypeslib.pyi +222 -0
  294. numpy/doc/ufuncs.py +138 -0
  295. numpy/dtypes.py +86 -0
  296. numpy/dtypes.pyi +627 -0
  297. numpy/exceptions.py +246 -0
  298. numpy/exceptions.pyi +27 -0
  299. numpy/f2py/__init__.py +80 -0
  300. numpy/f2py/__init__.pyi +5 -0
  301. numpy/f2py/__main__.py +5 -0
  302. numpy/f2py/__version__.py +1 -0
  303. numpy/f2py/__version__.pyi +1 -0
  304. numpy/f2py/_backends/__init__.py +6 -0
  305. numpy/f2py/_backends/__init__.pyi +5 -0
  306. numpy/f2py/_backends/_backend.py +44 -0
  307. numpy/f2py/_backends/_backend.pyi +46 -0
  308. numpy/f2py/_backends/_meson.py +244 -0
  309. numpy/f2py/_backends/_meson.pyi +61 -0
  310. numpy/f2py/_backends/meson.build.template +63 -0
  311. numpy/f2py/_isocbind.py +62 -0
  312. numpy/f2py/_isocbind.pyi +13 -0
  313. numpy/f2py/_src_pyf.py +247 -0
  314. numpy/f2py/_src_pyf.pyi +28 -0
  315. numpy/f2py/auxfuncs.py +1005 -0
  316. numpy/f2py/auxfuncs.pyi +259 -0
  317. numpy/f2py/capi_maps.py +811 -0
  318. numpy/f2py/capi_maps.pyi +33 -0
  319. numpy/f2py/cb_rules.py +649 -0
  320. numpy/f2py/cb_rules.pyi +17 -0
  321. numpy/f2py/cfuncs.py +1579 -0
  322. numpy/f2py/cfuncs.pyi +31 -0
  323. numpy/f2py/common_rules.py +145 -0
  324. numpy/f2py/common_rules.pyi +9 -0
  325. numpy/f2py/crackfortran.py +3727 -0
  326. numpy/f2py/crackfortran.pyi +254 -0
  327. numpy/f2py/diagnose.py +57 -0
  328. numpy/f2py/diagnose.pyi +1 -0
  329. numpy/f2py/f2py2e.py +755 -0
  330. numpy/f2py/f2py2e.pyi +69 -0
  331. numpy/f2py/f90mod_rules.py +281 -0
  332. numpy/f2py/f90mod_rules.pyi +16 -0
  333. numpy/f2py/func2subr.py +329 -0
  334. numpy/f2py/func2subr.pyi +7 -0
  335. numpy/f2py/rules.py +1641 -0
  336. numpy/f2py/rules.pyi +36 -0
  337. numpy/f2py/setup.cfg +3 -0
  338. numpy/f2py/src/fortranobject.c +1471 -0
  339. numpy/f2py/src/fortranobject.h +173 -0
  340. numpy/f2py/symbolic.py +1518 -0
  341. numpy/f2py/symbolic.pyi +220 -0
  342. numpy/f2py/tests/__init__.py +16 -0
  343. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  344. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  345. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +262 -0
  346. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  347. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  348. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  349. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  350. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  351. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  352. numpy/f2py/tests/src/callback/foo.f +62 -0
  353. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  354. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  355. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  356. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  357. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  358. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  359. numpy/f2py/tests/src/cli/hi77.f +3 -0
  360. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  361. numpy/f2py/tests/src/common/block.f +11 -0
  362. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  363. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  365. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  366. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  367. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  368. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  369. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  370. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  371. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  372. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  373. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  374. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  375. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  376. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  377. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  378. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  379. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  380. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  381. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  382. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  383. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  384. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  385. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  386. numpy/f2py/tests/src/inplace/foo.f +31 -0
  387. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  388. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  389. numpy/f2py/tests/src/mixed/foo.f +5 -0
  390. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  391. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  392. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  393. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  394. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  395. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  396. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  397. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  398. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  399. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  400. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  401. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  402. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  403. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  404. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  405. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  406. numpy/f2py/tests/src/regression/AB.inc +1 -0
  407. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  408. numpy/f2py/tests/src/regression/complex_struct_compat.f90 +8 -0
  409. numpy/f2py/tests/src/regression/complex_struct_compat.pyf +12 -0
  410. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  411. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  412. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  413. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  414. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  415. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  416. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  417. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  418. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  419. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  420. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  421. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  422. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  423. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  424. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  425. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  426. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  427. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  428. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  429. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  430. numpy/f2py/tests/src/routines/subrout.f +4 -0
  431. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  432. numpy/f2py/tests/src/size/foo.f90 +44 -0
  433. numpy/f2py/tests/src/string/char.f90 +29 -0
  434. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  435. numpy/f2py/tests/src/string/gh24008.f +8 -0
  436. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  437. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  438. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  439. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  440. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  441. numpy/f2py/tests/src/string/string.f +12 -0
  442. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  443. numpy/f2py/tests/test_abstract_interface.py +26 -0
  444. numpy/f2py/tests/test_array_from_pyobj.py +732 -0
  445. numpy/f2py/tests/test_assumed_shape.py +52 -0
  446. numpy/f2py/tests/test_block_docstring.py +16 -0
  447. numpy/f2py/tests/test_callback.py +262 -0
  448. numpy/f2py/tests/test_capi_maps.py +10 -0
  449. numpy/f2py/tests/test_character.py +644 -0
  450. numpy/f2py/tests/test_common.py +24 -0
  451. numpy/f2py/tests/test_crackfortran.py +427 -0
  452. numpy/f2py/tests/test_data.py +74 -0
  453. numpy/f2py/tests/test_docs.py +66 -0
  454. numpy/f2py/tests/test_f2cmap.py +20 -0
  455. numpy/f2py/tests/test_f2py2e.py +1006 -0
  456. numpy/f2py/tests/test_inplace.py +49 -0
  457. numpy/f2py/tests/test_isoc.py +56 -0
  458. numpy/f2py/tests/test_kind.py +53 -0
  459. numpy/f2py/tests/test_mixed.py +31 -0
  460. numpy/f2py/tests/test_modules.py +87 -0
  461. numpy/f2py/tests/test_parameter.py +121 -0
  462. numpy/f2py/tests/test_pyf_src.py +43 -0
  463. numpy/f2py/tests/test_quoted_character.py +19 -0
  464. numpy/f2py/tests/test_regression.py +202 -0
  465. numpy/f2py/tests/test_return_character.py +48 -0
  466. numpy/f2py/tests/test_return_complex.py +67 -0
  467. numpy/f2py/tests/test_return_integer.py +55 -0
  468. numpy/f2py/tests/test_return_logical.py +66 -0
  469. numpy/f2py/tests/test_return_real.py +109 -0
  470. numpy/f2py/tests/test_routines.py +29 -0
  471. numpy/f2py/tests/test_semicolon_split.py +76 -0
  472. numpy/f2py/tests/test_size.py +42 -0
  473. numpy/f2py/tests/test_string.py +102 -0
  474. numpy/f2py/tests/test_symbolic.py +501 -0
  475. numpy/f2py/tests/test_value_attrspec.py +15 -0
  476. numpy/f2py/tests/util.py +442 -0
  477. numpy/f2py/use_rules.py +100 -0
  478. numpy/f2py/use_rules.pyi +9 -0
  479. numpy/fft/__init__.py +213 -0
  480. numpy/fft/__init__.pyi +38 -0
  481. numpy/fft/_helper.py +235 -0
  482. numpy/fft/_helper.pyi +145 -0
  483. numpy/fft/_pocketfft.py +1693 -0
  484. numpy/fft/_pocketfft.pyi +1131 -0
  485. numpy/fft/_pocketfft_umath.cp315-win32.lib +0 -0
  486. numpy/fft/_pocketfft_umath.cp315-win32.pyd +0 -0
  487. numpy/fft/tests/__init__.py +0 -0
  488. numpy/fft/tests/test_helper.py +167 -0
  489. numpy/fft/tests/test_pocketfft.py +609 -0
  490. numpy/lib/__init__.py +90 -0
  491. numpy/lib/__init__.pyi +52 -0
  492. numpy/lib/_array_utils_impl.py +62 -0
  493. numpy/lib/_array_utils_impl.pyi +10 -0
  494. numpy/lib/_arraypad_impl.py +926 -0
  495. numpy/lib/_arraypad_impl.pyi +99 -0
  496. numpy/lib/_arraysetops_impl.py +1158 -0
  497. numpy/lib/_arraysetops_impl.pyi +460 -0
  498. numpy/lib/_arrayterator_impl.py +224 -0
  499. numpy/lib/_arrayterator_impl.pyi +45 -0
  500. numpy/lib/_datasource.py +700 -0
  501. numpy/lib/_datasource.pyi +30 -0
  502. numpy/lib/_format_impl.py +1038 -0
  503. numpy/lib/_format_impl.pyi +56 -0
  504. numpy/lib/_function_base_impl.py +5775 -0
  505. numpy/lib/_function_base_impl.pyi +2315 -0
  506. numpy/lib/_histograms_impl.py +1085 -0
  507. numpy/lib/_histograms_impl.pyi +273 -0
  508. numpy/lib/_index_tricks_impl.py +1048 -0
  509. numpy/lib/_index_tricks_impl.pyi +350 -0
  510. numpy/lib/_iotools.py +900 -0
  511. numpy/lib/_iotools.pyi +113 -0
  512. numpy/lib/_nanfunctions_impl.py +2006 -0
  513. numpy/lib/_nanfunctions_impl.pyi +48 -0
  514. numpy/lib/_npyio_impl.py +2491 -0
  515. numpy/lib/_npyio_impl.pyi +288 -0
  516. numpy/lib/_polynomial_impl.py +1467 -0
  517. numpy/lib/_polynomial_impl.pyi +435 -0
  518. numpy/lib/_scimath_impl.py +642 -0
  519. numpy/lib/_scimath_impl.pyi +93 -0
  520. numpy/lib/_shape_base_impl.py +1247 -0
  521. numpy/lib/_shape_base_impl.pyi +256 -0
  522. numpy/lib/_stride_tricks_impl.py +656 -0
  523. numpy/lib/_stride_tricks_impl.pyi +75 -0
  524. numpy/lib/_twodim_base_impl.py +1242 -0
  525. numpy/lib/_twodim_base_impl.pyi +397 -0
  526. numpy/lib/_type_check_impl.py +714 -0
  527. numpy/lib/_type_check_impl.pyi +450 -0
  528. numpy/lib/_ufunclike_impl.py +212 -0
  529. numpy/lib/_ufunclike_impl.pyi +41 -0
  530. numpy/lib/_user_array_impl.py +310 -0
  531. numpy/lib/_user_array_impl.pyi +229 -0
  532. numpy/lib/_utils_impl.py +541 -0
  533. numpy/lib/_utils_impl.pyi +18 -0
  534. numpy/lib/_version.py +153 -0
  535. numpy/lib/_version.pyi +22 -0
  536. numpy/lib/array_utils.py +7 -0
  537. numpy/lib/array_utils.pyi +6 -0
  538. numpy/lib/format.py +24 -0
  539. numpy/lib/format.pyi +24 -0
  540. numpy/lib/introspect.py +94 -0
  541. numpy/lib/introspect.pyi +3 -0
  542. numpy/lib/mixins.py +180 -0
  543. numpy/lib/mixins.pyi +78 -0
  544. numpy/lib/npyio.py +1 -0
  545. numpy/lib/npyio.pyi +5 -0
  546. numpy/lib/recfunctions.py +1681 -0
  547. numpy/lib/recfunctions.pyi +436 -0
  548. numpy/lib/scimath.py +13 -0
  549. numpy/lib/scimath.pyi +12 -0
  550. numpy/lib/stride_tricks.py +1 -0
  551. numpy/lib/stride_tricks.pyi +4 -0
  552. numpy/lib/tests/__init__.py +0 -0
  553. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  554. numpy/lib/tests/data/py2-objarr.npy +0 -0
  555. numpy/lib/tests/data/py2-objarr.npz +0 -0
  556. numpy/lib/tests/data/py3-objarr.npy +0 -0
  557. numpy/lib/tests/data/py3-objarr.npz +0 -0
  558. numpy/lib/tests/data/python3.npy +0 -0
  559. numpy/lib/tests/data/win64python2.npy +0 -0
  560. numpy/lib/tests/test__datasource.py +328 -0
  561. numpy/lib/tests/test__iotools.py +358 -0
  562. numpy/lib/tests/test__version.py +64 -0
  563. numpy/lib/tests/test_array_utils.py +32 -0
  564. numpy/lib/tests/test_arraypad.py +1427 -0
  565. numpy/lib/tests/test_arraysetops.py +1304 -0
  566. numpy/lib/tests/test_arrayterator.py +45 -0
  567. numpy/lib/tests/test_format.py +1043 -0
  568. numpy/lib/tests/test_function_base.py +4787 -0
  569. numpy/lib/tests/test_histograms.py +855 -0
  570. numpy/lib/tests/test_index_tricks.py +703 -0
  571. numpy/lib/tests/test_io.py +2733 -0
  572. numpy/lib/tests/test_loadtxt.py +1077 -0
  573. numpy/lib/tests/test_mixins.py +215 -0
  574. numpy/lib/tests/test_nanfunctions.py +1449 -0
  575. numpy/lib/tests/test_packbits.py +374 -0
  576. numpy/lib/tests/test_polynomial.py +333 -0
  577. numpy/lib/tests/test_recfunctions.py +1042 -0
  578. numpy/lib/tests/test_regression.py +231 -0
  579. numpy/lib/tests/test_shape_base.py +813 -0
  580. numpy/lib/tests/test_stride_tricks.py +890 -0
  581. numpy/lib/tests/test_twodim_base.py +564 -0
  582. numpy/lib/tests/test_type_check.py +473 -0
  583. numpy/lib/tests/test_ufunclike.py +121 -0
  584. numpy/lib/tests/test_utils.py +80 -0
  585. numpy/lib/user_array.py +1 -0
  586. numpy/lib/user_array.pyi +1 -0
  587. numpy/linalg/__init__.py +95 -0
  588. numpy/linalg/__init__.pyi +71 -0
  589. numpy/linalg/_linalg.py +3649 -0
  590. numpy/linalg/_linalg.pyi +1230 -0
  591. numpy/linalg/_umath_linalg.cp315-win32.lib +0 -0
  592. numpy/linalg/_umath_linalg.cp315-win32.pyd +0 -0
  593. numpy/linalg/_umath_linalg.pyi +60 -0
  594. numpy/linalg/lapack_lite.cp315-win32.lib +0 -0
  595. numpy/linalg/lapack_lite.cp315-win32.pyd +0 -0
  596. numpy/linalg/lapack_lite.pyi +143 -0
  597. numpy/linalg/tests/__init__.py +0 -0
  598. numpy/linalg/tests/test_deprecations.py +21 -0
  599. numpy/linalg/tests/test_linalg.py +2492 -0
  600. numpy/linalg/tests/test_regression.py +191 -0
  601. numpy/ma/API_CHANGES.txt +135 -0
  602. numpy/ma/LICENSE +24 -0
  603. numpy/ma/README.rst +236 -0
  604. numpy/ma/__init__.py +53 -0
  605. numpy/ma/__init__.pyi +458 -0
  606. numpy/ma/core.py +9000 -0
  607. numpy/ma/core.pyi +4767 -0
  608. numpy/ma/extras.py +2266 -0
  609. numpy/ma/extras.pyi +770 -0
  610. numpy/ma/mrecords.py +739 -0
  611. numpy/ma/mrecords.pyi +313 -0
  612. numpy/ma/tests/__init__.py +0 -0
  613. numpy/ma/tests/test_arrayobject.py +40 -0
  614. numpy/ma/tests/test_core.py +6112 -0
  615. numpy/ma/tests/test_deprecations.py +73 -0
  616. numpy/ma/tests/test_extras.py +1945 -0
  617. numpy/ma/tests/test_mrecords.py +495 -0
  618. numpy/ma/tests/test_old_ma.py +939 -0
  619. numpy/ma/tests/test_regression.py +83 -0
  620. numpy/ma/tests/test_subclassing.py +469 -0
  621. numpy/ma/testutils.py +294 -0
  622. numpy/ma/testutils.pyi +69 -0
  623. numpy/matlib.py +380 -0
  624. numpy/matlib.pyi +580 -0
  625. numpy/matrixlib/__init__.py +12 -0
  626. numpy/matrixlib/__init__.pyi +3 -0
  627. numpy/matrixlib/defmatrix.py +1117 -0
  628. numpy/matrixlib/defmatrix.pyi +211 -0
  629. numpy/matrixlib/tests/__init__.py +0 -0
  630. numpy/matrixlib/tests/test_defmatrix.py +475 -0
  631. numpy/matrixlib/tests/test_interaction.py +360 -0
  632. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  633. numpy/matrixlib/tests/test_matrix_linalg.py +110 -0
  634. numpy/matrixlib/tests/test_multiarray.py +17 -0
  635. numpy/matrixlib/tests/test_numeric.py +18 -0
  636. numpy/matrixlib/tests/test_regression.py +31 -0
  637. numpy/polynomial/__init__.py +187 -0
  638. numpy/polynomial/__init__.pyi +31 -0
  639. numpy/polynomial/_polybase.py +1191 -0
  640. numpy/polynomial/_polybase.pyi +255 -0
  641. numpy/polynomial/_polytypes.pyi +536 -0
  642. numpy/polynomial/chebyshev.py +2053 -0
  643. numpy/polynomial/chebyshev.pyi +173 -0
  644. numpy/polynomial/hermite.py +1794 -0
  645. numpy/polynomial/hermite.pyi +110 -0
  646. numpy/polynomial/hermite_e.py +1692 -0
  647. numpy/polynomial/hermite_e.pyi +110 -0
  648. numpy/polynomial/laguerre.py +1729 -0
  649. numpy/polynomial/laguerre.pyi +103 -0
  650. numpy/polynomial/legendre.py +1655 -0
  651. numpy/polynomial/legendre.pyi +103 -0
  652. numpy/polynomial/polynomial.py +1683 -0
  653. numpy/polynomial/polynomial.pyi +112 -0
  654. numpy/polynomial/polyutils.py +759 -0
  655. numpy/polynomial/polyutils.pyi +295 -0
  656. numpy/polynomial/tests/__init__.py +0 -0
  657. numpy/polynomial/tests/test_chebyshev.py +639 -0
  658. numpy/polynomial/tests/test_classes.py +625 -0
  659. numpy/polynomial/tests/test_hermite.py +574 -0
  660. numpy/polynomial/tests/test_hermite_e.py +575 -0
  661. numpy/polynomial/tests/test_laguerre.py +556 -0
  662. numpy/polynomial/tests/test_legendre.py +587 -0
  663. numpy/polynomial/tests/test_polynomial.py +713 -0
  664. numpy/polynomial/tests/test_polyutils.py +123 -0
  665. numpy/polynomial/tests/test_printing.py +562 -0
  666. numpy/polynomial/tests/test_symbol.py +217 -0
  667. numpy/py.typed +0 -0
  668. numpy/random/LICENSE.md +71 -0
  669. numpy/random/__init__.pxd +14 -0
  670. numpy/random/__init__.py +213 -0
  671. numpy/random/__init__.pyi +124 -0
  672. numpy/random/_bounded_integers.cp315-win32.lib +0 -0
  673. numpy/random/_bounded_integers.cp315-win32.pyd +0 -0
  674. numpy/random/_bounded_integers.pxd +38 -0
  675. numpy/random/_bounded_integers.pyi +1 -0
  676. numpy/random/_common.cp315-win32.lib +0 -0
  677. numpy/random/_common.cp315-win32.pyd +0 -0
  678. numpy/random/_common.pxd +110 -0
  679. numpy/random/_common.pyi +17 -0
  680. numpy/random/_examples/cffi/extending.py +44 -0
  681. numpy/random/_examples/cffi/parse.py +53 -0
  682. numpy/random/_examples/cython/extending.pyx +77 -0
  683. numpy/random/_examples/cython/extending_distributions.pyx +117 -0
  684. numpy/random/_examples/cython/meson.build +53 -0
  685. numpy/random/_examples/numba/extending.py +86 -0
  686. numpy/random/_examples/numba/extending_distributions.py +67 -0
  687. numpy/random/_generator.cp315-win32.lib +0 -0
  688. numpy/random/_generator.cp315-win32.pyd +0 -0
  689. numpy/random/_generator.pyi +769 -0
  690. numpy/random/_mt19937.cp315-win32.lib +0 -0
  691. numpy/random/_mt19937.cp315-win32.pyd +0 -0
  692. numpy/random/_mt19937.pyi +27 -0
  693. numpy/random/_pcg64.cp315-win32.lib +0 -0
  694. numpy/random/_pcg64.cp315-win32.pyd +0 -0
  695. numpy/random/_pcg64.pyi +36 -0
  696. numpy/random/_philox.cp315-win32.lib +0 -0
  697. numpy/random/_philox.cp315-win32.pyd +0 -0
  698. numpy/random/_philox.pyi +36 -0
  699. numpy/random/_pickle.py +88 -0
  700. numpy/random/_pickle.pyi +43 -0
  701. numpy/random/_sfc64.cp315-win32.lib +0 -0
  702. numpy/random/_sfc64.cp315-win32.pyd +0 -0
  703. numpy/random/_sfc64.pyi +25 -0
  704. numpy/random/bit_generator.cp315-win32.lib +0 -0
  705. numpy/random/bit_generator.cp315-win32.pyd +0 -0
  706. numpy/random/bit_generator.pxd +35 -0
  707. numpy/random/bit_generator.pyi +122 -0
  708. numpy/random/c_distributions.pxd +119 -0
  709. numpy/random/lib/npyrandom.lib +0 -0
  710. numpy/random/mtrand.cp315-win32.lib +0 -0
  711. numpy/random/mtrand.cp315-win32.pyd +0 -0
  712. numpy/random/mtrand.pyi +996 -0
  713. numpy/random/tests/__init__.py +0 -0
  714. numpy/random/tests/data/__init__.py +0 -0
  715. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  716. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  717. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  718. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  719. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  720. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  721. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  722. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  723. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  724. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  725. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  726. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  727. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  728. numpy/random/tests/test_direct.py +620 -0
  729. numpy/random/tests/test_extending.py +129 -0
  730. numpy/random/tests/test_generator_mt19937.py +2830 -0
  731. numpy/random/tests/test_generator_mt19937_regressions.py +240 -0
  732. numpy/random/tests/test_random.py +1723 -0
  733. numpy/random/tests/test_randomstate.py +2107 -0
  734. numpy/random/tests/test_randomstate_regression.py +249 -0
  735. numpy/random/tests/test_regression.py +174 -0
  736. numpy/random/tests/test_seed_sequence.py +103 -0
  737. numpy/random/tests/test_smoke.py +882 -0
  738. numpy/rec/__init__.py +2 -0
  739. numpy/rec/__init__.pyi +23 -0
  740. numpy/strings/__init__.py +2 -0
  741. numpy/strings/__init__.pyi +97 -0
  742. numpy/testing/__init__.py +22 -0
  743. numpy/testing/__init__.pyi +107 -0
  744. numpy/testing/_private/__init__.py +0 -0
  745. numpy/testing/_private/__init__.pyi +0 -0
  746. numpy/testing/_private/extbuild.py +247 -0
  747. numpy/testing/_private/extbuild.pyi +25 -0
  748. numpy/testing/_private/utils.py +2899 -0
  749. numpy/testing/_private/utils.pyi +501 -0
  750. numpy/testing/overrides.py +84 -0
  751. numpy/testing/overrides.pyi +10 -0
  752. numpy/testing/print_coercion_tables.py +207 -0
  753. numpy/testing/print_coercion_tables.pyi +26 -0
  754. numpy/testing/tests/__init__.py +0 -0
  755. numpy/testing/tests/test_utils.py +2147 -0
  756. numpy/tests/__init__.py +0 -0
  757. numpy/tests/test__all__.py +10 -0
  758. numpy/tests/test_configtool.py +51 -0
  759. numpy/tests/test_ctypeslib.py +406 -0
  760. numpy/tests/test_lazyloading.py +35 -0
  761. numpy/tests/test_matlib.py +59 -0
  762. numpy/tests/test_numpy_config.py +47 -0
  763. numpy/tests/test_numpy_version.py +54 -0
  764. numpy/tests/test_public_api.py +723 -0
  765. numpy/tests/test_reloading.py +69 -0
  766. numpy/tests/test_scripts.py +45 -0
  767. numpy/tests/test_warnings.py +81 -0
  768. numpy/typing/__init__.py +225 -0
  769. numpy/typing/__init__.pyi +8 -0
  770. numpy/typing/mypy_plugin.py +200 -0
  771. numpy/typing/tests/__init__.py +0 -0
  772. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  773. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  774. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  775. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  776. numpy/typing/tests/data/fail/arrayprint.pyi +15 -0
  777. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  778. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  779. numpy/typing/tests/data/fail/char.pyi +60 -0
  780. numpy/typing/tests/data/fail/chararray.pyi +61 -0
  781. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  782. numpy/typing/tests/data/fail/constants.pyi +3 -0
  783. numpy/typing/tests/data/fail/datasource.pyi +16 -0
  784. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  785. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  786. numpy/typing/tests/data/fail/flatiter.pyi +38 -0
  787. numpy/typing/tests/data/fail/fromnumeric.pyi +149 -0
  788. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  789. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  790. numpy/typing/tests/data/fail/lib_function_base.pyi +60 -0
  791. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  792. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  793. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  794. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  795. numpy/typing/tests/data/fail/ma.pyi +152 -0
  796. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  797. numpy/typing/tests/data/fail/modules.pyi +17 -0
  798. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  799. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  800. numpy/typing/tests/data/fail/ndarray_misc.pyi +49 -0
  801. numpy/typing/tests/data/fail/nditer.pyi +7 -0
  802. numpy/typing/tests/data/fail/nested_sequence.pyi +17 -0
  803. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  804. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  805. numpy/typing/tests/data/fail/random.pyi +62 -0
  806. numpy/typing/tests/data/fail/rec.pyi +17 -0
  807. numpy/typing/tests/data/fail/scalars.pyi +86 -0
  808. numpy/typing/tests/data/fail/shape.pyi +7 -0
  809. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  810. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  811. numpy/typing/tests/data/fail/strings.pyi +41 -0
  812. numpy/typing/tests/data/fail/testing.pyi +28 -0
  813. numpy/typing/tests/data/fail/twodim_base.pyi +39 -0
  814. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  815. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  816. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  817. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  818. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  819. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  820. numpy/typing/tests/data/mypy.ini +8 -0
  821. numpy/typing/tests/data/pass/arithmetic.py +614 -0
  822. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  823. numpy/typing/tests/data/pass/array_like.py +37 -0
  824. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  825. numpy/typing/tests/data/pass/arrayterator.py +28 -0
  826. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  827. numpy/typing/tests/data/pass/comparisons.py +316 -0
  828. numpy/typing/tests/data/pass/dtype.py +57 -0
  829. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  830. numpy/typing/tests/data/pass/flatiter.py +26 -0
  831. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  832. numpy/typing/tests/data/pass/index_tricks.py +62 -0
  833. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  834. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  835. numpy/typing/tests/data/pass/lib_version.py +18 -0
  836. numpy/typing/tests/data/pass/literal.py +52 -0
  837. numpy/typing/tests/data/pass/ma.py +199 -0
  838. numpy/typing/tests/data/pass/mod.py +149 -0
  839. numpy/typing/tests/data/pass/modules.py +45 -0
  840. numpy/typing/tests/data/pass/multiarray.py +77 -0
  841. numpy/typing/tests/data/pass/ndarray_conversion.py +81 -0
  842. numpy/typing/tests/data/pass/ndarray_misc.py +199 -0
  843. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  844. numpy/typing/tests/data/pass/nditer.py +4 -0
  845. numpy/typing/tests/data/pass/numeric.py +90 -0
  846. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  847. numpy/typing/tests/data/pass/random.py +1498 -0
  848. numpy/typing/tests/data/pass/recfunctions.py +164 -0
  849. numpy/typing/tests/data/pass/scalars.py +262 -0
  850. numpy/typing/tests/data/pass/shape.py +19 -0
  851. numpy/typing/tests/data/pass/simple.py +170 -0
  852. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  853. numpy/typing/tests/data/pass/ufunclike.py +52 -0
  854. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  855. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  856. numpy/typing/tests/data/reveal/arithmetic.pyi +726 -0
  857. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  858. numpy/typing/tests/data/reveal/array_constructors.pyi +331 -0
  859. numpy/typing/tests/data/reveal/arraypad.pyi +32 -0
  860. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  861. numpy/typing/tests/data/reveal/arraysetops.pyi +80 -0
  862. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  863. numpy/typing/tests/data/reveal/bitwise_ops.pyi +166 -0
  864. numpy/typing/tests/data/reveal/char.pyi +228 -0
  865. numpy/typing/tests/data/reveal/chararray.pyi +138 -0
  866. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  867. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  868. numpy/typing/tests/data/reveal/ctypeslib.pyi +86 -0
  869. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  870. numpy/typing/tests/data/reveal/dtype.pyi +166 -0
  871. numpy/typing/tests/data/reveal/einsumfunc.pyi +46 -0
  872. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  873. numpy/typing/tests/data/reveal/fft.pyi +189 -0
  874. numpy/typing/tests/data/reveal/flatiter.pyi +86 -0
  875. numpy/typing/tests/data/reveal/fromnumeric.pyi +574 -0
  876. numpy/typing/tests/data/reveal/getlimits.pyi +53 -0
  877. numpy/typing/tests/data/reveal/histograms.pyi +69 -0
  878. numpy/typing/tests/data/reveal/index_tricks.pyi +148 -0
  879. numpy/typing/tests/data/reveal/lib_function_base.pyi +413 -0
  880. numpy/typing/tests/data/reveal/lib_polynomial.pyi +147 -0
  881. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  882. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  883. numpy/typing/tests/data/reveal/linalg.pyi +517 -0
  884. numpy/typing/tests/data/reveal/ma.pyi +1103 -0
  885. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  886. numpy/typing/tests/data/reveal/memmap.pyi +21 -0
  887. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  888. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  889. numpy/typing/tests/data/reveal/multiarray.pyi +336 -0
  890. numpy/typing/tests/data/reveal/nbit_base_example.pyi +17 -0
  891. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +79 -0
  892. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +83 -0
  893. numpy/typing/tests/data/reveal/ndarray_misc.pyi +428 -0
  894. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +47 -0
  895. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  896. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  897. numpy/typing/tests/data/reveal/npyio.pyi +85 -0
  898. numpy/typing/tests/data/reveal/numeric.pyi +176 -0
  899. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  900. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +216 -0
  901. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +218 -0
  902. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  903. numpy/typing/tests/data/reveal/random.pyi +1357 -0
  904. numpy/typing/tests/data/reveal/rec.pyi +177 -0
  905. numpy/typing/tests/data/reveal/scalars.pyi +288 -0
  906. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  907. numpy/typing/tests/data/reveal/shape_base.pyi +84 -0
  908. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  909. numpy/typing/tests/data/reveal/strings.pyi +198 -0
  910. numpy/typing/tests/data/reveal/testing.pyi +196 -0
  911. numpy/typing/tests/data/reveal/twodim_base.pyi +231 -0
  912. numpy/typing/tests/data/reveal/type_check.pyi +94 -0
  913. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  914. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  915. numpy/typing/tests/data/reveal/ufuncs.pyi +142 -0
  916. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  917. numpy/typing/tests/test_isfile.py +35 -0
  918. numpy/typing/tests/test_runtime.py +103 -0
  919. numpy/typing/tests/test_typing.py +207 -0
  920. numpy/version.py +11 -0
  921. numpy/version.pyi +9 -0
  922. numpy-2.5.2.dist-info/METADATA +139 -0
  923. numpy-2.5.2.dist-info/RECORD +942 -0
  924. numpy-2.5.2.dist-info/WHEEL +4 -0
  925. numpy-2.5.2.dist-info/entry_points.txt +13 -0
  926. numpy-2.5.2.dist-info/licenses/LICENSE.txt +914 -0
  927. numpy-2.5.2.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt +21 -0
  928. numpy-2.5.2.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING +14 -0
  929. numpy-2.5.2.dist-info/licenses/numpy/_core/src/highway/LICENSE +371 -0
  930. numpy-2.5.2.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt +27 -0
  931. numpy-2.5.2.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md +28 -0
  932. numpy-2.5.2.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE +30 -0
  933. numpy-2.5.2.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md +25 -0
  934. numpy-2.5.2.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt +48 -0
  935. numpy-2.5.2.dist-info/licenses/numpy/ma/LICENSE +24 -0
  936. numpy-2.5.2.dist-info/licenses/numpy/random/LICENSE.md +71 -0
  937. numpy-2.5.2.dist-info/licenses/numpy/random/src/distributions/LICENSE.md +61 -0
  938. numpy-2.5.2.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md +61 -0
  939. numpy-2.5.2.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md +22 -0
  940. numpy-2.5.2.dist-info/licenses/numpy/random/src/philox/LICENSE.md +31 -0
  941. numpy-2.5.2.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md +27 -0
  942. numpy-2.5.2.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md +9 -0
@@ -0,0 +1,2107 @@
1
+ import contextlib
2
+ import ctypes
3
+ import inspect
4
+ import operator
5
+ import os
6
+ import pickle
7
+ import sys
8
+ import types
9
+ import warnings
10
+ from itertools import permutations
11
+ from typing import Any
12
+
13
+ import hypothesis
14
+ import pytest
15
+ from hypothesis.extra import numpy as hynp
16
+
17
+ import numpy as np
18
+ import numpy.dtypes
19
+ from numpy._core._multiarray_tests import create_custom_field_dtype
20
+ from numpy._core._rational_tests import rational, rational2
21
+ from numpy.testing import (
22
+ HAS_REFCOUNT,
23
+ IS_64BIT,
24
+ IS_WASM,
25
+ assert_,
26
+ assert_array_equal,
27
+ assert_equal,
28
+ assert_raises,
29
+ )
30
+ from numpy.testing._private.utils import requires_deep_recursion
31
+
32
+
33
+ def assert_dtype_equal(a, b):
34
+ assert_equal(a, b)
35
+ assert_equal(hash(a), hash(b),
36
+ "two equivalent types do not hash to the same value !")
37
+
38
+ def assert_dtype_not_equal(a, b):
39
+ assert_(a != b)
40
+ assert_(hash(a) != hash(b),
41
+ "two different types hash to the same value !")
42
+
43
+ class TestBuiltin:
44
+ @pytest.mark.parametrize('t', [int, float, complex, np.int32, str, object])
45
+ def test_run(self, t):
46
+ """Only test hash runs at all."""
47
+ dt = np.dtype(t)
48
+ hash(dt)
49
+
50
+ @pytest.mark.parametrize('t', [int, float])
51
+ def test_dtype(self, t):
52
+ # Make sure equivalent byte order char hash the same (e.g. < and = on
53
+ # little endian)
54
+ dt = np.dtype(t)
55
+ dt2 = dt.newbyteorder("<")
56
+ dt3 = dt.newbyteorder(">")
57
+ if dt == dt2:
58
+ assert_(dt.byteorder != dt2.byteorder, "bogus test")
59
+ assert_dtype_equal(dt, dt2)
60
+ else:
61
+ assert_(dt.byteorder != dt3.byteorder, "bogus test")
62
+ assert_dtype_equal(dt, dt3)
63
+
64
+ def test_equivalent_dtype_hashing(self):
65
+ # Make sure equivalent dtypes with different type num hash equal
66
+ uintp = np.dtype(np.uintp)
67
+ if uintp.itemsize == 4:
68
+ left = uintp
69
+ right = np.dtype(np.uint32)
70
+ else:
71
+ left = uintp
72
+ right = np.dtype(np.ulonglong)
73
+ assert_(left == right)
74
+ assert_(hash(left) == hash(right))
75
+
76
+ def test_invalid_types(self):
77
+ # Make sure invalid type strings raise an error
78
+
79
+ assert_raises(TypeError, np.dtype, 'O3')
80
+ assert_raises(TypeError, np.dtype, 'O5')
81
+ assert_raises(TypeError, np.dtype, 'O7')
82
+ assert_raises(TypeError, np.dtype, 'b3')
83
+ assert_raises(TypeError, np.dtype, 'h4')
84
+ assert_raises(TypeError, np.dtype, 'I5')
85
+ assert_raises(TypeError, np.dtype, 'e3')
86
+ assert_raises(TypeError, np.dtype, 'f5')
87
+
88
+ if np.dtype('g').itemsize == 8 or np.dtype('g').itemsize == 16:
89
+ assert_raises(TypeError, np.dtype, 'g12')
90
+ elif np.dtype('g').itemsize == 12:
91
+ assert_raises(TypeError, np.dtype, 'g16')
92
+
93
+ if np.dtype('l').itemsize == 8:
94
+ assert_raises(TypeError, np.dtype, 'l4')
95
+ assert_raises(TypeError, np.dtype, 'L4')
96
+ else:
97
+ assert_raises(TypeError, np.dtype, 'l8')
98
+ assert_raises(TypeError, np.dtype, 'L8')
99
+
100
+ if np.dtype('q').itemsize == 8:
101
+ assert_raises(TypeError, np.dtype, 'q4')
102
+ assert_raises(TypeError, np.dtype, 'Q4')
103
+ else:
104
+ assert_raises(TypeError, np.dtype, 'q8')
105
+ assert_raises(TypeError, np.dtype, 'Q8')
106
+
107
+ # Make sure negative-sized dtype raises an error
108
+ assert_raises(TypeError, np.dtype, 'S-1')
109
+ assert_raises(TypeError, np.dtype, 'U-1')
110
+ assert_raises(TypeError, np.dtype, 'V-1')
111
+
112
+ def test_richcompare_invalid_dtype_equality(self):
113
+ # Make sure objects that cannot be converted to valid
114
+ # dtypes results in False/True when compared to valid dtypes.
115
+ # Here 7 cannot be converted to dtype. No exceptions should be raised
116
+
117
+ assert not np.dtype(np.int32) == 7, "dtype richcompare failed for =="
118
+ assert np.dtype(np.int32) != 7, "dtype richcompare failed for !="
119
+
120
+ @pytest.mark.parametrize(
121
+ 'operation',
122
+ [operator.le, operator.lt, operator.ge, operator.gt])
123
+ def test_richcompare_invalid_dtype_comparison(self, operation):
124
+ # Make sure TypeError is raised for comparison operators
125
+ # for invalid dtypes. Here 7 is an invalid dtype.
126
+
127
+ with pytest.raises(TypeError):
128
+ operation(np.dtype(np.int32), 7)
129
+
130
+ @pytest.mark.parametrize("dtype",
131
+ ['Bool', 'Bytes0', 'Complex32', 'Complex64',
132
+ 'Datetime64', 'Float16', 'Float32', 'Float64',
133
+ 'Int8', 'Int16', 'Int32', 'Int64',
134
+ 'Object0', 'Str0', 'Timedelta64',
135
+ 'UInt8', 'UInt16', 'Uint32', 'UInt32',
136
+ 'Uint64', 'UInt64', 'Void0',
137
+ "Float128", "Complex128"])
138
+ def test_numeric_style_types_are_invalid(self, dtype):
139
+ with assert_raises(TypeError):
140
+ np.dtype(dtype)
141
+
142
+ def test_expired_dtypes_with_bad_bytesize(self):
143
+ match: str = r".*removed in NumPy 2.0.*"
144
+ with pytest.raises(TypeError, match=match):
145
+ np.dtype("int0")
146
+ with pytest.raises(TypeError, match=match):
147
+ np.dtype("uint0")
148
+ with pytest.raises(TypeError, match=match):
149
+ np.dtype("bool8")
150
+ with pytest.raises(TypeError, match=match):
151
+ np.dtype("bytes0")
152
+ with pytest.raises(TypeError, match=match):
153
+ np.dtype("str0")
154
+ with pytest.raises(TypeError, match=match):
155
+ np.dtype("object0")
156
+ with pytest.raises(TypeError, match=match):
157
+ np.dtype("void0")
158
+
159
+ @pytest.mark.parametrize(
160
+ 'value',
161
+ ['m8', 'M8', 'datetime64', 'timedelta64',
162
+ 'i4, (2,3)f8, f4', 'S3, 3u8, (3,4)S10',
163
+ '>f', '<f', '=f', '|f',
164
+ ])
165
+ def test_dtype_bytes_str_equivalence(self, value):
166
+ bytes_value = value.encode('ascii')
167
+ from_bytes = np.dtype(bytes_value)
168
+ from_str = np.dtype(value)
169
+ assert_dtype_equal(from_bytes, from_str)
170
+
171
+ def test_dtype_from_bytes(self):
172
+ # Empty bytes object
173
+ assert_raises(TypeError, np.dtype, b'')
174
+ # Byte order indicator, but no type
175
+ assert_raises(TypeError, np.dtype, b'|')
176
+
177
+ # Single character with ordinal < NPY_NTYPES_LEGACY returns
178
+ # type by index into _builtin_descrs
179
+ assert_dtype_equal(np.dtype(bytes([0])), np.dtype('bool'))
180
+ assert_dtype_equal(np.dtype(bytes([17])), np.dtype(object))
181
+
182
+ # Single character where value is a valid type code
183
+ assert_dtype_equal(np.dtype(b'f'), np.dtype('float32'))
184
+
185
+ # Bytes with non-ascii values raise errors
186
+ assert_raises(TypeError, np.dtype, b'\xff')
187
+ assert_raises(TypeError, np.dtype, b's\xff')
188
+
189
+ def test_bad_param(self):
190
+ # Can't give a size that's too small
191
+ assert_raises(ValueError, np.dtype,
192
+ {'names': ['f0', 'f1'],
193
+ 'formats': ['i4', 'i1'],
194
+ 'offsets': [0, 4],
195
+ 'itemsize': 4})
196
+ # If alignment is enabled, the alignment (4) must divide the itemsize
197
+ assert_raises(ValueError, np.dtype,
198
+ {'names': ['f0', 'f1'],
199
+ 'formats': ['i4', 'i1'],
200
+ 'offsets': [0, 4],
201
+ 'itemsize': 9}, align=True)
202
+ # If alignment is enabled, the individual fields must be aligned
203
+ assert_raises(ValueError, np.dtype,
204
+ {'names': ['f0', 'f1'],
205
+ 'formats': ['i1', 'f4'],
206
+ 'offsets': [0, 2]}, align=True)
207
+
208
+ def test_field_order_equality(self):
209
+ x = np.dtype({'names': ['A', 'B'],
210
+ 'formats': ['i4', 'f4'],
211
+ 'offsets': [0, 4]})
212
+ y = np.dtype({'names': ['B', 'A'],
213
+ 'formats': ['i4', 'f4'],
214
+ 'offsets': [4, 0]})
215
+ assert_equal(x == y, False)
216
+ # This is a safe cast (not equiv) due to the different names:
217
+ assert np.can_cast(x, y, casting="safe")
218
+
219
+ @pytest.mark.parametrize(
220
+ ["type_char", "char_size", "scalar_type"],
221
+ [["U", 4, np.str_],
222
+ ["S", 1, np.bytes_]])
223
+ def test_create_string_dtypes_directly(
224
+ self, type_char, char_size, scalar_type):
225
+ dtype_class = type(np.dtype(type_char))
226
+
227
+ dtype = dtype_class(8)
228
+ assert dtype.type is scalar_type
229
+ assert dtype.itemsize == 8 * char_size
230
+
231
+ def test_create_invalid_string_errors(self):
232
+ one_too_big = np.iinfo(np.intc).max + 1
233
+ with pytest.raises(TypeError):
234
+ type(np.dtype("U"))(one_too_big // 4)
235
+
236
+ with pytest.raises(TypeError):
237
+ # Code coverage for very large numbers:
238
+ type(np.dtype("U"))(np.iinfo(np.intp).max // 4 + 1)
239
+
240
+ if one_too_big < sys.maxsize:
241
+ with pytest.raises(TypeError):
242
+ type(np.dtype("S"))(one_too_big)
243
+
244
+ with pytest.raises(ValueError):
245
+ type(np.dtype("U"))(-1)
246
+
247
+ # OverflowError on 32 bit
248
+ with pytest.raises((TypeError, OverflowError)):
249
+ # see gh-26556
250
+ type(np.dtype("S"))(2**61)
251
+
252
+ with pytest.raises(TypeError):
253
+ np.dtype("S1234hello")
254
+
255
+ def test_leading_zero_parsing(self):
256
+ dt1 = np.dtype('S010')
257
+ dt2 = np.dtype('S10')
258
+
259
+ assert dt1 == dt2
260
+ assert repr(dt1) == "dtype('S10')"
261
+ assert dt1.itemsize == 10
262
+
263
+
264
+ class TestRecord:
265
+ def test_equivalent_record(self):
266
+ """Test whether equivalent record dtypes hash the same."""
267
+ a = np.dtype([('yo', int)])
268
+ b = np.dtype([('yo', int)])
269
+ assert_dtype_equal(a, b)
270
+
271
+ def test_different_names(self):
272
+ # In theory, they may hash the same (collision) ?
273
+ a = np.dtype([('yo', int)])
274
+ b = np.dtype([('ye', int)])
275
+ assert_dtype_not_equal(a, b)
276
+
277
+ def test_different_titles(self):
278
+ # In theory, they may hash the same (collision) ?
279
+ a = np.dtype({'names': ['r', 'b'],
280
+ 'formats': ['u1', 'u1'],
281
+ 'titles': ['Red pixel', 'Blue pixel']})
282
+ b = np.dtype({'names': ['r', 'b'],
283
+ 'formats': ['u1', 'u1'],
284
+ 'titles': ['RRed pixel', 'Blue pixel']})
285
+ assert_dtype_not_equal(a, b)
286
+
287
+ @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
288
+ def test_refcount_dictionary_setting(self):
289
+ names = ["name1"]
290
+ formats = ["f8"]
291
+ titles = ["t1"]
292
+ offsets = [0]
293
+ d = {"names": names, "formats": formats, "titles": titles, "offsets": offsets}
294
+ refcounts = {k: sys.getrefcount(i) for k, i in d.items()}
295
+ np.dtype(d)
296
+ refcounts_new = {k: sys.getrefcount(i) for k, i in d.items()}
297
+ assert refcounts == refcounts_new
298
+
299
+ def test_mutate(self):
300
+ # Mutating a dtype should reset the cached hash value.
301
+ # NOTE: Mutating should be deprecated, but new API added to replace it.
302
+ a = np.dtype([('yo', int)])
303
+ b = np.dtype([('yo', int)])
304
+ c = np.dtype([('ye', int)])
305
+ assert_dtype_equal(a, b)
306
+ assert_dtype_not_equal(a, c)
307
+ a.names = ['ye']
308
+ assert_dtype_equal(a, c)
309
+ assert_dtype_not_equal(a, b)
310
+ state = b.__reduce__()[2]
311
+ a.__setstate__(state)
312
+ assert_dtype_equal(a, b)
313
+ assert_dtype_not_equal(a, c)
314
+
315
+ def test_init_simple_structured(self):
316
+ dt1 = np.dtype("i, i")
317
+ assert dt1.names == ("f0", "f1")
318
+
319
+ dt2 = np.dtype("i,")
320
+ assert dt2.names == ("f0",)
321
+
322
+ def test_mutate_error(self):
323
+ # NOTE: Mutating should be deprecated, but new API added to replace it.
324
+ a = np.dtype("i,i")
325
+
326
+ with pytest.raises(ValueError, match="must replace all names at once"):
327
+ a.names = ["f0"]
328
+
329
+ with pytest.raises(ValueError, match=".*and not string"):
330
+ a.names = ["f0", b"not a unicode name"]
331
+
332
+ def test_not_lists(self):
333
+ """Test if an appropriate exception is raised when passing bad values to
334
+ the dtype constructor.
335
+ """
336
+ assert_raises(TypeError, np.dtype,
337
+ {"names": {'A', 'B'}, "formats": ['f8', 'i4']})
338
+ assert_raises(TypeError, np.dtype,
339
+ {"names": ['A', 'B'], "formats": {'f8', 'i4'}})
340
+
341
+ def test_aligned_size(self):
342
+ # Check that structured dtypes get padded to an aligned size
343
+ dt = np.dtype('i4, i1', align=True)
344
+ assert_equal(dt.itemsize, 8)
345
+ dt = np.dtype([('f0', 'i4'), ('f1', 'i1')], align=True)
346
+ assert_equal(dt.itemsize, 8)
347
+ dt = np.dtype({'names': ['f0', 'f1'],
348
+ 'formats': ['i4', 'u1'],
349
+ 'offsets': [0, 4]}, align=True)
350
+ assert_equal(dt.itemsize, 8)
351
+ dt = np.dtype({'f0': ('i4', 0), 'f1': ('u1', 4)}, align=True)
352
+ assert_equal(dt.itemsize, 8)
353
+ # Nesting should preserve that alignment
354
+ dt1 = np.dtype([('f0', 'i4'),
355
+ ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]),
356
+ ('f2', 'i1')], align=True)
357
+ assert_equal(dt1.itemsize, 20)
358
+ dt2 = np.dtype({'names': ['f0', 'f1', 'f2'],
359
+ 'formats': ['i4',
360
+ [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')],
361
+ 'i1'],
362
+ 'offsets': [0, 4, 16]}, align=True)
363
+ assert_equal(dt2.itemsize, 20)
364
+ dt3 = np.dtype({'f0': ('i4', 0),
365
+ 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4),
366
+ 'f2': ('i1', 16)}, align=True)
367
+ assert_equal(dt3.itemsize, 20)
368
+ assert_equal(dt1, dt2)
369
+ assert_equal(dt2, dt3)
370
+ # Nesting should preserve packing
371
+ dt1 = np.dtype([('f0', 'i4'),
372
+ ('f1', [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')]),
373
+ ('f2', 'i1')], align=False)
374
+ assert_equal(dt1.itemsize, 11)
375
+ dt2 = np.dtype({'names': ['f0', 'f1', 'f2'],
376
+ 'formats': ['i4',
377
+ [('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')],
378
+ 'i1'],
379
+ 'offsets': [0, 4, 10]}, align=False)
380
+ assert_equal(dt2.itemsize, 11)
381
+ dt3 = np.dtype({'f0': ('i4', 0),
382
+ 'f1': ([('f1', 'i1'), ('f2', 'i4'), ('f3', 'i1')], 4),
383
+ 'f2': ('i1', 10)}, align=False)
384
+ assert_equal(dt3.itemsize, 11)
385
+ assert_equal(dt1, dt2)
386
+ assert_equal(dt2, dt3)
387
+ # Array of subtype should preserve alignment
388
+ dt1 = np.dtype([('a', '|i1'),
389
+ ('b', [('f0', '<i2'),
390
+ ('f1', '<f4')], 2)], align=True)
391
+ assert_equal(dt1.descr, [('a', '|i1'), ('', '|V3'),
392
+ ('b', [('f0', '<i2'), ('', '|V2'),
393
+ ('f1', '<f4')], (2,))])
394
+
395
+ def test_empty_struct_alignment(self):
396
+ # Empty dtypes should have an alignment of 1
397
+ dt = np.dtype([], align=True)
398
+ assert_equal(dt.alignment, 1)
399
+ dt = np.dtype([('f0', [])], align=True)
400
+ assert_equal(dt.alignment, 1)
401
+ dt = np.dtype({'names': [],
402
+ 'formats': [],
403
+ 'offsets': []}, align=True)
404
+ assert_equal(dt.alignment, 1)
405
+ dt = np.dtype({'names': ['f0'],
406
+ 'formats': [[]],
407
+ 'offsets': [0]}, align=True)
408
+ assert_equal(dt.alignment, 1)
409
+
410
+ def test_union_struct(self):
411
+ # Should be able to create union dtypes
412
+ dt = np.dtype({'names': ['f0', 'f1', 'f2'], 'formats': ['<u4', '<u2', '<u2'],
413
+ 'offsets': [0, 0, 2]}, align=True)
414
+ assert_equal(dt.itemsize, 4)
415
+ a = np.array([3], dtype='<u4').view(dt)
416
+ a['f1'] = 10
417
+ a['f2'] = 36
418
+ assert_equal(a['f0'], 10 + 36 * 256 * 256)
419
+ # Should be able to specify fields out of order
420
+ dt = np.dtype({'names': ['f0', 'f1', 'f2'], 'formats': ['<u4', '<u2', '<u2'],
421
+ 'offsets': [4, 0, 2]}, align=True)
422
+ assert_equal(dt.itemsize, 8)
423
+ # field name should not matter: assignment is by position
424
+ dt2 = np.dtype({'names': ['f2', 'f0', 'f1'],
425
+ 'formats': ['<u4', '<u2', '<u2'],
426
+ 'offsets': [4, 0, 2]}, align=True)
427
+ vals = [(0, 1, 2), (3, 2**15 - 1, 4)]
428
+ vals2 = [(0, 1, 2), (3, 2**15 - 1, 4)]
429
+ a = np.array(vals, dt)
430
+ b = np.array(vals2, dt2)
431
+ assert_equal(a.astype(dt2), b)
432
+ assert_equal(b.astype(dt), a)
433
+ assert_equal(a.view(dt2), b)
434
+ assert_equal(b.view(dt), a)
435
+ # Should not be able to overlap objects with other types
436
+ assert_raises(TypeError, np.dtype,
437
+ {'names': ['f0', 'f1'],
438
+ 'formats': ['O', 'i1'],
439
+ 'offsets': [0, 2]})
440
+ assert_raises(TypeError, np.dtype,
441
+ {'names': ['f0', 'f1'],
442
+ 'formats': ['i4', 'O'],
443
+ 'offsets': [0, 3]})
444
+ assert_raises(TypeError, np.dtype,
445
+ {'names': ['f0', 'f1'],
446
+ 'formats': [[('a', 'O')], 'i1'],
447
+ 'offsets': [0, 2]})
448
+ assert_raises(TypeError, np.dtype,
449
+ {'names': ['f0', 'f1'],
450
+ 'formats': ['i4', [('a', 'O')]],
451
+ 'offsets': [0, 3]})
452
+ # Out of order should still be ok, however
453
+ dt = np.dtype({'names': ['f0', 'f1'],
454
+ 'formats': ['i1', 'O'],
455
+ 'offsets': [np.dtype('intp').itemsize, 0]})
456
+
457
+ @pytest.mark.parametrize(["obj", "dtype", "expected"],
458
+ [([], ("2f4"), np.empty((0, 2), dtype="f4")),
459
+ (3, "(3,)f4", [3, 3, 3]),
460
+ (np.float64(2), "(2,)f4", [2, 2]),
461
+ ([((0, 1), (1, 2)), ((2,),)], '(2,2)f4', None),
462
+ (["1", "2"], "2i", None)])
463
+ def test_subarray_list(self, obj, dtype, expected):
464
+ dtype = np.dtype(dtype)
465
+ res = np.array(obj, dtype=dtype)
466
+
467
+ if expected is None:
468
+ # iterate the 1-d list to fill the array
469
+ expected = np.empty(len(obj), dtype=dtype)
470
+ for i in range(len(expected)):
471
+ expected[i] = obj[i]
472
+
473
+ assert_array_equal(res, expected)
474
+
475
+ def test_parenthesized_single_number(self):
476
+ with pytest.raises(TypeError, match="not understood"):
477
+ np.dtype("(2)f4")
478
+
479
+ # Deprecation also tested in
480
+ # test_deprecations.py::TestDeprecatedDTypeParenthesizedRepeatCount
481
+ # Left here to allow easy conversion to an exception check.
482
+ with pytest.warns(DeprecationWarning,
483
+ match="parenthesized single number"):
484
+ np.dtype("(2)f4,")
485
+
486
+ def test_comma_datetime(self):
487
+ dt = np.dtype('M8[D],datetime64[Y],i8')
488
+ assert_equal(dt, np.dtype([('f0', 'M8[D]'),
489
+ ('f1', 'datetime64[Y]'),
490
+ ('f2', 'i8')]))
491
+
492
+ def test_from_dictproxy(self):
493
+ # Tests for PR #5920
494
+ dt = np.dtype({'names': ['a', 'b'], 'formats': ['i4', 'f4']})
495
+ assert_dtype_equal(dt, np.dtype(dt.fields))
496
+ dt2 = np.dtype((np.void, dt.fields))
497
+ assert_equal(dt2.fields, dt.fields)
498
+
499
+ def test_from_dict_with_zero_width_field(self):
500
+ # Regression test for #6430 / #2196
501
+ dt = np.dtype([('val1', np.float32, (0,)), ('val2', int)])
502
+ dt2 = np.dtype({'names': ['val1', 'val2'],
503
+ 'formats': [(np.float32, (0,)), int]})
504
+
505
+ assert_dtype_equal(dt, dt2)
506
+ assert_equal(dt.fields['val1'][0].itemsize, 0)
507
+ assert_equal(dt.itemsize, dt.fields['val2'][0].itemsize)
508
+
509
+ def test_bool_commastring(self):
510
+ d = np.dtype('?,?,?') # raises?
511
+ assert_equal(len(d.names), 3)
512
+ for n in d.names:
513
+ assert_equal(d.fields[n][0], np.dtype('?'))
514
+
515
+ def test_nonint_offsets(self):
516
+ # gh-8059
517
+ def make_dtype(off):
518
+ return np.dtype({'names': ['A'], 'formats': ['i4'],
519
+ 'offsets': [off]})
520
+
521
+ assert_raises(TypeError, make_dtype, 'ASD')
522
+ assert_raises(OverflowError, make_dtype, 2**70)
523
+ assert_raises(TypeError, make_dtype, 2.3)
524
+ assert_raises(ValueError, make_dtype, -10)
525
+
526
+ # no errors here:
527
+ dt = make_dtype(np.uint32(0))
528
+ np.zeros(1, dtype=dt)[0].item()
529
+
530
+ def test_fields_by_index(self):
531
+ dt = np.dtype([('a', np.int8), ('b', np.float32, 3)])
532
+ assert_dtype_equal(dt[0], np.dtype(np.int8))
533
+ assert_dtype_equal(dt[1], np.dtype((np.float32, 3)))
534
+ assert_dtype_equal(dt[-1], dt[1])
535
+ assert_dtype_equal(dt[-2], dt[0])
536
+ assert_raises(IndexError, lambda: dt[-3])
537
+
538
+ assert_raises(TypeError, operator.getitem, dt, 3.0)
539
+
540
+ assert_equal(dt[1], dt[np.int8(1)])
541
+
542
+ @pytest.mark.parametrize('align_flag', [False, True])
543
+ def test_multifield_index(self, align_flag):
544
+ # indexing with a list produces subfields
545
+ # the align flag should be preserved
546
+ dt = np.dtype([
547
+ (('title', 'col1'), '<U20'), ('A', '<f8'), ('B', '<f8')
548
+ ], align=align_flag)
549
+
550
+ dt_sub = dt[['B', 'col1']]
551
+ assert_equal(
552
+ dt_sub,
553
+ np.dtype({
554
+ 'names': ['B', 'col1'],
555
+ 'formats': ['<f8', '<U20'],
556
+ 'offsets': [88, 0],
557
+ 'titles': [None, 'title'],
558
+ 'itemsize': 96
559
+ })
560
+ )
561
+ assert_equal(dt_sub.isalignedstruct, align_flag)
562
+
563
+ dt_sub = dt[['B']]
564
+ assert_equal(
565
+ dt_sub,
566
+ np.dtype({
567
+ 'names': ['B'],
568
+ 'formats': ['<f8'],
569
+ 'offsets': [88],
570
+ 'itemsize': 96
571
+ })
572
+ )
573
+ assert_equal(dt_sub.isalignedstruct, align_flag)
574
+
575
+ dt_sub = dt[[]]
576
+ assert_equal(
577
+ dt_sub,
578
+ np.dtype({
579
+ 'names': [],
580
+ 'formats': [],
581
+ 'offsets': [],
582
+ 'itemsize': 96
583
+ })
584
+ )
585
+ assert_equal(dt_sub.isalignedstruct, align_flag)
586
+
587
+ assert_raises(TypeError, operator.getitem, dt, ())
588
+ assert_raises(TypeError, operator.getitem, dt, [1, 2, 3])
589
+ assert_raises(TypeError, operator.getitem, dt, ['col1', 2])
590
+ assert_raises(KeyError, operator.getitem, dt, ['fake'])
591
+ assert_raises(KeyError, operator.getitem, dt, ['title'])
592
+ assert_raises(ValueError, operator.getitem, dt, ['col1', 'col1'])
593
+
594
+ def test_partial_dict(self):
595
+ # 'names' is missing
596
+ assert_raises(ValueError, np.dtype,
597
+ {'formats': ['i4', 'i4'], 'f0': ('i4', 0), 'f1': ('i4', 4)})
598
+
599
+ def test_fieldless_views(self):
600
+ a = np.zeros(2, dtype={'names': [], 'formats': [], 'offsets': [],
601
+ 'itemsize': 8})
602
+ assert_raises(ValueError, a.view, np.dtype([]))
603
+
604
+ d = np.dtype((np.dtype([]), 10))
605
+ assert_equal(d.shape, (10,))
606
+ assert_equal(d.itemsize, 0)
607
+ assert_equal(d.base, np.dtype([]))
608
+
609
+ arr = np.fromiter((() for i in range(10)), [])
610
+ assert_equal(arr.dtype, np.dtype([]))
611
+ assert_raises(ValueError, np.frombuffer, b'', dtype=[])
612
+ assert_equal(np.frombuffer(b'', dtype=[], count=2),
613
+ np.empty(2, dtype=[]))
614
+
615
+ assert_raises(ValueError, np.dtype, ([], 'f8'))
616
+ assert_raises(ValueError, np.zeros(1, dtype='i4').view, [])
617
+
618
+ assert_equal(np.zeros(2, dtype=[]) == np.zeros(2, dtype=[]),
619
+ np.ones(2, dtype=bool))
620
+
621
+ assert_equal(np.zeros((1, 2), dtype=[]) == a,
622
+ np.ones((1, 2), dtype=bool))
623
+
624
+ def test_nonstructured_with_object(self):
625
+ # See gh-23277, the dtype here thinks it contain objects, if the
626
+ # assert about that fails, the test becomes meaningless (which is OK)
627
+ arr = np.recarray((0,), dtype="O")
628
+ assert arr.dtype.names is None # no fields
629
+ assert arr.dtype.hasobject # but claims to contain objects
630
+ del arr # the deletion failed previously.
631
+
632
+ def test_structured_out_of_range(self):
633
+ # Regression test for gh-29270 against over-eager optimization of
634
+ # copying of structured dtype: do not copy when dtype has holes
635
+ # because the itemsize was explicitly given.
636
+ dtype = np.dtype(dict(names=["a"], formats=["i4"], itemsize=8))
637
+ raw_arr = np.zeros(10, dtype="i8")
638
+ arr1 = raw_arr.view(dtype)
639
+ arr2 = np.full(10, -1, dtype="i8").view(dtype)
640
+ # This should only fill in the i4 field of `dtype`:
641
+ arr1[...] = arr2
642
+ assert (raw_arr.view("i4")[1::2] == 0).all()
643
+
644
+
645
+ class TestSubarray:
646
+ def test_single_subarray(self):
647
+ a = np.dtype((int, (2)))
648
+ b = np.dtype((int, (2,)))
649
+ assert_dtype_equal(a, b)
650
+
651
+ assert_equal(type(a.subdtype[1]), tuple)
652
+ assert_equal(type(b.subdtype[1]), tuple)
653
+
654
+ def test_equivalent_record(self):
655
+ """Test whether equivalent subarray dtypes hash the same."""
656
+ a = np.dtype((int, (2, 3)))
657
+ b = np.dtype((int, (2, 3)))
658
+ assert_dtype_equal(a, b)
659
+
660
+ def test_nonequivalent_record(self):
661
+ """Test whether different subarray dtypes hash differently."""
662
+ a = np.dtype((int, (2, 3)))
663
+ b = np.dtype((int, (3, 2)))
664
+ assert_dtype_not_equal(a, b)
665
+
666
+ a = np.dtype((int, (2, 3)))
667
+ b = np.dtype((int, (2, 2)))
668
+ assert_dtype_not_equal(a, b)
669
+
670
+ a = np.dtype((int, (1, 2, 3)))
671
+ b = np.dtype((int, (1, 2)))
672
+ assert_dtype_not_equal(a, b)
673
+
674
+ def test_shape_equal(self):
675
+ """Test some data types that are equal"""
676
+ assert_dtype_equal(np.dtype('f8'), np.dtype(('f8', ())))
677
+ assert_dtype_equal(np.dtype('(1,)f8'), np.dtype(('f8', 1)))
678
+ assert np.dtype(('f8', 1)).shape == (1,)
679
+ assert_dtype_equal(np.dtype((int, 2)), np.dtype((int, (2,))))
680
+ assert_dtype_equal(np.dtype(('<f4', (3, 2))), np.dtype(('<f4', (3, 2))))
681
+ d = ([('a', 'f4', (1, 2)), ('b', 'f8', (3, 1))], (3, 2))
682
+ assert_dtype_equal(np.dtype(d), np.dtype(d))
683
+
684
+ def test_shape_simple(self):
685
+ """Test some simple cases that shouldn't be equal"""
686
+ assert_dtype_not_equal(np.dtype('f8'), np.dtype(('f8', (1,))))
687
+ assert_dtype_not_equal(np.dtype(('f8', (1,))), np.dtype(('f8', (1, 1))))
688
+ assert_dtype_not_equal(np.dtype(('f4', (3, 2))), np.dtype(('f4', (2, 3))))
689
+
690
+ def test_shape_monster(self):
691
+ """Test some more complicated cases that shouldn't be equal"""
692
+ assert_dtype_not_equal(
693
+ np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))),
694
+ np.dtype(([('a', 'f4', (1, 2)), ('b', 'f8', (1, 3))], (2, 2))))
695
+ assert_dtype_not_equal(
696
+ np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))),
697
+ np.dtype(([('a', 'f4', (2, 1)), ('b', 'i8', (1, 3))], (2, 2))))
698
+ assert_dtype_not_equal(
699
+ np.dtype(([('a', 'f4', (2, 1)), ('b', 'f8', (1, 3))], (2, 2))),
700
+ np.dtype(([('e', 'f8', (1, 3)), ('d', 'f4', (2, 1))], (2, 2))))
701
+ assert_dtype_not_equal(
702
+ np.dtype(([('a', [('a', 'i4', 6)], (2, 1)), ('b', 'f8', (1, 3))], (2, 2))),
703
+ np.dtype(([('a', [('a', 'u4', 6)], (2, 1)), ('b', 'f8', (1, 3))], (2, 2))))
704
+
705
+ def test_shape_sequence(self):
706
+ # Any sequence of integers should work as shape, but the result
707
+ # should be a tuple (immutable) of base type integers.
708
+ a = np.array([1, 2, 3], dtype=np.int16)
709
+ l = [1, 2, 3]
710
+ # Array gets converted
711
+ dt = np.dtype([('a', 'f4', a)])
712
+ assert_(isinstance(dt['a'].shape, tuple))
713
+ assert_(isinstance(dt['a'].shape[0], int))
714
+ # List gets converted
715
+ dt = np.dtype([('a', 'f4', l)])
716
+ assert_(isinstance(dt['a'].shape, tuple))
717
+ #
718
+
719
+ class IntLike:
720
+ def __index__(self):
721
+ return 3
722
+
723
+ def __int__(self):
724
+ # (a PyNumber_Check fails without __int__)
725
+ return 3
726
+
727
+ dt = np.dtype([('a', 'f4', IntLike())])
728
+ assert_(isinstance(dt['a'].shape, tuple))
729
+ assert_(isinstance(dt['a'].shape[0], int))
730
+ dt = np.dtype([('a', 'f4', (IntLike(),))])
731
+ assert_(isinstance(dt['a'].shape, tuple))
732
+ assert_(isinstance(dt['a'].shape[0], int))
733
+
734
+ def test_shape_matches_ndim(self):
735
+ dt = np.dtype([('a', 'f4', ())])
736
+ assert_equal(dt['a'].shape, ())
737
+ assert_equal(dt['a'].ndim, 0)
738
+
739
+ dt = np.dtype([('a', 'f4')])
740
+ assert_equal(dt['a'].shape, ())
741
+ assert_equal(dt['a'].ndim, 0)
742
+
743
+ dt = np.dtype([('a', 'f4', 4)])
744
+ assert_equal(dt['a'].shape, (4,))
745
+ assert_equal(dt['a'].ndim, 1)
746
+
747
+ dt = np.dtype([('a', 'f4', (1, 2, 3))])
748
+ assert_equal(dt['a'].shape, (1, 2, 3))
749
+ assert_equal(dt['a'].ndim, 3)
750
+
751
+ def test_shape_invalid(self):
752
+ # Check that the shape is valid.
753
+ max_int = np.iinfo(np.intc).max
754
+ max_intp = np.iinfo(np.intp).max
755
+ # Too large values (the datatype is part of this)
756
+ assert_raises(ValueError, np.dtype, [('a', 'f4', max_int // 4 + 1)])
757
+ assert_raises(ValueError, np.dtype, [('a', 'f4', max_int + 1)])
758
+ assert_raises(ValueError, np.dtype, [('a', 'f4', (max_int, 2))])
759
+ # Takes a different code path (fails earlier:
760
+ assert_raises(ValueError, np.dtype, [('a', 'f4', max_intp + 1)])
761
+ # Negative values
762
+ assert_raises(ValueError, np.dtype, [('a', 'f4', -1)])
763
+ assert_raises(ValueError, np.dtype, [('a', 'f4', (-1, -1))])
764
+
765
+ def test_alignment(self):
766
+ # Check that subarrays are aligned
767
+ t1 = np.dtype('(1,)i4', align=True)
768
+ t2 = np.dtype('2i4', align=True)
769
+ assert_equal(t1.alignment, t2.alignment)
770
+
771
+ def test_aligned_empty(self):
772
+ # Mainly regression test for gh-19696: construction failed completely
773
+ dt = np.dtype([], align=True)
774
+ assert dt == np.dtype([])
775
+ dt = np.dtype({"names": [], "formats": [], "itemsize": 0}, align=True)
776
+ assert dt == np.dtype([])
777
+
778
+ def test_subarray_base_item(self):
779
+ arr = np.ones(3, dtype=[("f", "i", 3)])
780
+ # Extracting the field "absorbs" the subarray into a view:
781
+ assert arr["f"].base is arr
782
+ # Extract the structured item, and then check the tuple component:
783
+ item = arr.item(0)
784
+ assert type(item) is tuple and len(item) == 1
785
+ assert item[0].base is arr
786
+
787
+ def test_subarray_cast_copies(self):
788
+ # Older versions of NumPy did NOT copy, but they got the ownership
789
+ # wrong (not actually knowing the correct base!). Versions since 1.21
790
+ # (I think) crashed fairly reliable. This defines the correct behavior
791
+ # as a copy. Keeping the ownership would be possible (but harder)
792
+ arr = np.ones(3, dtype=[("f", "i", 3)])
793
+ cast = arr.astype(object)
794
+ for fields in cast:
795
+ assert type(fields) is tuple and len(fields) == 1
796
+ subarr = fields[0]
797
+ assert subarr.base is None
798
+ assert subarr.flags.owndata
799
+
800
+
801
+ def iter_struct_object_dtypes():
802
+ """
803
+ Iterates over a few complex dtypes and object pattern which
804
+ fill the array with a given object (defaults to a singleton).
805
+
806
+ Yields
807
+ ------
808
+ dtype : dtype
809
+ pattern : tuple
810
+ Structured tuple for use with `np.array`.
811
+ count : int
812
+ Number of objects stored in the dtype.
813
+ singleton : object
814
+ A singleton object. The returned pattern is constructed so that
815
+ all objects inside the datatype are set to the singleton.
816
+ """
817
+ obj = object()
818
+
819
+ dt = np.dtype([('b', 'O', (2, 3))])
820
+ p = ([[obj] * 3] * 2,)
821
+ yield pytest.param(dt, p, 6, obj, id="<subarray>")
822
+
823
+ dt = np.dtype([('a', 'i4'), ('b', 'O', (2, 3))])
824
+ p = (0, [[obj] * 3] * 2)
825
+ yield pytest.param(dt, p, 6, obj, id="<subarray in field>")
826
+
827
+ dt = np.dtype([('a', 'i4'),
828
+ ('b', [('ba', 'O'), ('bb', 'i1')], (2, 3))])
829
+ p = (0, [[(obj, 0)] * 3] * 2)
830
+ yield pytest.param(dt, p, 6, obj, id="<structured subarray 1>")
831
+
832
+ dt = np.dtype([('a', 'i4'),
833
+ ('b', [('ba', 'O'), ('bb', 'O')], (2, 3))])
834
+ p = (0, [[(obj, obj)] * 3] * 2)
835
+ yield pytest.param(dt, p, 12, obj, id="<structured subarray 2>")
836
+
837
+
838
+ class TestStructuredDtypeSparseFields:
839
+ """Tests subarray fields which contain sparse dtypes so that
840
+ not all memory is used by the dtype work. Such dtype's should
841
+ leave the underlying memory unchanged.
842
+ """
843
+ dtype = np.dtype([('a', {'names': ['aa', 'ab'], 'formats': ['f', 'f'],
844
+ 'offsets': [0, 4]}, (2, 3))])
845
+ sparse_dtype = np.dtype([('a', {'names': ['ab'], 'formats': ['f'],
846
+ 'offsets': [4]}, (2, 3))])
847
+
848
+ def test_sparse_field_assignment(self):
849
+ arr = np.zeros(3, self.dtype)
850
+ sparse_arr = arr.view(self.sparse_dtype)
851
+
852
+ sparse_arr[...] = np.finfo(np.float32).max
853
+ # dtype is reduced when accessing the field, so shape is (3, 2, 3):
854
+ assert_array_equal(arr["a"]["aa"], np.zeros((3, 2, 3)))
855
+
856
+ def test_sparse_field_assignment_fancy(self):
857
+ # Fancy assignment goes to the copyswap function for complex types:
858
+ arr = np.zeros(3, self.dtype)
859
+ sparse_arr = arr.view(self.sparse_dtype)
860
+
861
+ sparse_arr[[0, 1, 2]] = np.finfo(np.float32).max
862
+ # dtype is reduced when accessing the field, so shape is (3, 2, 3):
863
+ assert_array_equal(arr["a"]["aa"], np.zeros((3, 2, 3)))
864
+
865
+
866
+ class TestMonsterType:
867
+ """Test deeply nested subtypes."""
868
+
869
+ def test1(self):
870
+ simple1 = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'],
871
+ 'titles': ['Red pixel', 'Blue pixel']})
872
+ a = np.dtype([('yo', int), ('ye', simple1),
873
+ ('yi', np.dtype((int, (3, 2))))])
874
+ b = np.dtype([('yo', int), ('ye', simple1),
875
+ ('yi', np.dtype((int, (3, 2))))])
876
+ assert_dtype_equal(a, b)
877
+
878
+ c = np.dtype([('yo', int), ('ye', simple1),
879
+ ('yi', np.dtype((a, (3, 2))))])
880
+ d = np.dtype([('yo', int), ('ye', simple1),
881
+ ('yi', np.dtype((a, (3, 2))))])
882
+ assert_dtype_equal(c, d)
883
+
884
+ @requires_deep_recursion
885
+ def test_list_recursion(self):
886
+ l = []
887
+ l.append(('f', l))
888
+ with pytest.raises(RecursionError):
889
+ np.dtype(l)
890
+
891
+ @requires_deep_recursion
892
+ def test_tuple_recursion(self):
893
+ d = np.int32
894
+ for i in range(100000):
895
+ d = (d, (1,))
896
+ # depending on OS and Python version, this might succeed
897
+ # see gh-30370 and cpython issue #142253
898
+ with contextlib.suppress(RecursionError):
899
+ np.dtype(d)
900
+
901
+ @pytest.mark.thread_unsafe(reason="Sets global threading stack size")
902
+ @pytest.mark.skipif(IS_WASM, reason="wasm doesn't have support for threads")
903
+ def test_deep_subarray_dtype_dealloc(self):
904
+ import threading
905
+
906
+ import numpy as np
907
+
908
+ def build_and_drop():
909
+ d = np.dtype(np.int32)
910
+ for _ in range(200000):
911
+ d = np.dtype((d, (1,)))
912
+ # hold a second reference so teardown exercises stopping
913
+ # and resuming
914
+ held = d.base
915
+ del d
916
+ del held
917
+
918
+ # small stack size to fail reliably if deallocation is recusive
919
+ old_stack_size = threading.stack_size(1024 * 1024)
920
+ try:
921
+ t = threading.Thread(target=build_and_drop)
922
+ t.start()
923
+ t.join()
924
+ finally:
925
+ threading.stack_size(old_stack_size)
926
+
927
+ @requires_deep_recursion
928
+ def test_dict_recursion(self):
929
+ d = {"names": ['self'], "formats": [None], "offsets": [0]}
930
+ d['formats'][0] = d
931
+ with pytest.raises(RecursionError):
932
+ np.dtype(d)
933
+
934
+
935
+ class TestMetadata:
936
+ def test_no_metadata(self):
937
+ d = np.dtype(int)
938
+ assert_(d.metadata is None)
939
+
940
+ def test_metadata_takes_dict(self):
941
+ d = np.dtype(int, metadata={'datum': 1})
942
+ assert_(d.metadata == {'datum': 1})
943
+
944
+ def test_metadata_rejects_nondict(self):
945
+ assert_raises(TypeError, np.dtype, int, metadata='datum')
946
+ assert_raises(TypeError, np.dtype, int, metadata=1)
947
+ assert_raises(TypeError, np.dtype, int, metadata=None)
948
+
949
+ def test_nested_metadata(self):
950
+ d = np.dtype([('a', np.dtype(int, metadata={'datum': 1}))])
951
+ assert_(d['a'].metadata == {'datum': 1})
952
+
953
+ def test_base_metadata_copied(self):
954
+ d = np.dtype((np.void, np.dtype('i4,i4', metadata={'datum': 1})))
955
+ assert_(d.metadata == {'datum': 1})
956
+
957
+ class TestString:
958
+ def test_complex_dtype_str(self):
959
+ dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),
960
+ ('rtile', '>f4', (64, 36))], (3,)),
961
+ ('bottom', [('bleft', ('>f4', (8, 64)), (1,)),
962
+ ('bright', '>f4', (8, 36))])])
963
+ assert_equal(str(dt),
964
+ "[('top', [('tiles', ('>f4', (64, 64)), (1,)), "
965
+ "('rtile', '>f4', (64, 36))], (3,)), "
966
+ "('bottom', [('bleft', ('>f4', (8, 64)), (1,)), "
967
+ "('bright', '>f4', (8, 36))])]")
968
+
969
+ # If the sticky aligned flag is set to True, it makes the
970
+ # str() function use a dict representation with an 'aligned' flag
971
+ dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),
972
+ ('rtile', '>f4', (64, 36))],
973
+ (3,)),
974
+ ('bottom', [('bleft', ('>f4', (8, 64)), (1,)),
975
+ ('bright', '>f4', (8, 36))])],
976
+ align=True)
977
+ assert_equal(str(dt),
978
+ "{'names': ['top', 'bottom'],"
979
+ " 'formats': [([('tiles', ('>f4', (64, 64)), (1,)), "
980
+ "('rtile', '>f4', (64, 36))], (3,)), "
981
+ "[('bleft', ('>f4', (8, 64)), (1,)), "
982
+ "('bright', '>f4', (8, 36))]],"
983
+ " 'offsets': [0, 76800],"
984
+ " 'itemsize': 80000,"
985
+ " 'aligned': True}")
986
+ with np.printoptions(legacy='1.21'):
987
+ assert_equal(str(dt),
988
+ "{'names':['top','bottom'], "
989
+ "'formats':[([('tiles', ('>f4', (64, 64)), (1,)), "
990
+ "('rtile', '>f4', (64, 36))], (3,)),"
991
+ "[('bleft', ('>f4', (8, 64)), (1,)), "
992
+ "('bright', '>f4', (8, 36))]], "
993
+ "'offsets':[0,76800], "
994
+ "'itemsize':80000, "
995
+ "'aligned':True}")
996
+ assert_equal(np.dtype(eval(str(dt))), dt)
997
+
998
+ dt = np.dtype({'names': ['r', 'g', 'b'], 'formats': ['u1', 'u1', 'u1'],
999
+ 'offsets': [0, 1, 2],
1000
+ 'titles': ['Red pixel', 'Green pixel', 'Blue pixel']})
1001
+ assert_equal(str(dt),
1002
+ "[(('Red pixel', 'r'), 'u1'), "
1003
+ "(('Green pixel', 'g'), 'u1'), "
1004
+ "(('Blue pixel', 'b'), 'u1')]")
1005
+
1006
+ dt = np.dtype({'names': ['rgba', 'r', 'g', 'b'],
1007
+ 'formats': ['<u4', 'u1', 'u1', 'u1'],
1008
+ 'offsets': [0, 0, 1, 2],
1009
+ 'titles': ['Color', 'Red pixel',
1010
+ 'Green pixel', 'Blue pixel']})
1011
+ assert_equal(str(dt),
1012
+ "{'names': ['rgba', 'r', 'g', 'b'],"
1013
+ " 'formats': ['<u4', 'u1', 'u1', 'u1'],"
1014
+ " 'offsets': [0, 0, 1, 2],"
1015
+ " 'titles': ['Color', 'Red pixel', "
1016
+ "'Green pixel', 'Blue pixel'],"
1017
+ " 'itemsize': 4}")
1018
+
1019
+ dt = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'],
1020
+ 'offsets': [0, 2],
1021
+ 'titles': ['Red pixel', 'Blue pixel']})
1022
+ assert_equal(str(dt),
1023
+ "{'names': ['r', 'b'],"
1024
+ " 'formats': ['u1', 'u1'],"
1025
+ " 'offsets': [0, 2],"
1026
+ " 'titles': ['Red pixel', 'Blue pixel'],"
1027
+ " 'itemsize': 3}")
1028
+
1029
+ dt = np.dtype([('a', '<m8[D]'), ('b', '<M8[us]')])
1030
+ assert_equal(str(dt),
1031
+ "[('a', '<m8[D]'), ('b', '<M8[us]')]")
1032
+
1033
+ def test_repr_structured(self):
1034
+ dt = np.dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)),
1035
+ ('rtile', '>f4', (64, 36))], (3,)),
1036
+ ('bottom', [('bleft', ('>f4', (8, 64)), (1,)),
1037
+ ('bright', '>f4', (8, 36))])])
1038
+ assert_equal(repr(dt),
1039
+ "dtype([('top', [('tiles', ('>f4', (64, 64)), (1,)), "
1040
+ "('rtile', '>f4', (64, 36))], (3,)), "
1041
+ "('bottom', [('bleft', ('>f4', (8, 64)), (1,)), "
1042
+ "('bright', '>f4', (8, 36))])])")
1043
+
1044
+ dt = np.dtype({'names': ['r', 'g', 'b'], 'formats': ['u1', 'u1', 'u1'],
1045
+ 'offsets': [0, 1, 2],
1046
+ 'titles': ['Red pixel', 'Green pixel', 'Blue pixel']},
1047
+ align=True)
1048
+ assert_equal(repr(dt),
1049
+ "dtype([(('Red pixel', 'r'), 'u1'), "
1050
+ "(('Green pixel', 'g'), 'u1'), "
1051
+ "(('Blue pixel', 'b'), 'u1')], align=True)")
1052
+
1053
+ def test_repr_structured_not_packed(self):
1054
+ dt = np.dtype({'names': ['rgba', 'r', 'g', 'b'],
1055
+ 'formats': ['<u4', 'u1', 'u1', 'u1'],
1056
+ 'offsets': [0, 0, 1, 2],
1057
+ 'titles': ['Color', 'Red pixel',
1058
+ 'Green pixel', 'Blue pixel']}, align=True)
1059
+ assert_equal(repr(dt),
1060
+ "dtype({'names': ['rgba', 'r', 'g', 'b'],"
1061
+ " 'formats': ['<u4', 'u1', 'u1', 'u1'],"
1062
+ " 'offsets': [0, 0, 1, 2],"
1063
+ " 'titles': ['Color', 'Red pixel', "
1064
+ "'Green pixel', 'Blue pixel'],"
1065
+ " 'itemsize': 4}, align=True)")
1066
+
1067
+ dt = np.dtype({'names': ['r', 'b'], 'formats': ['u1', 'u1'],
1068
+ 'offsets': [0, 2],
1069
+ 'titles': ['Red pixel', 'Blue pixel'],
1070
+ 'itemsize': 4})
1071
+ assert_equal(repr(dt),
1072
+ "dtype({'names': ['r', 'b'], "
1073
+ "'formats': ['u1', 'u1'], "
1074
+ "'offsets': [0, 2], "
1075
+ "'titles': ['Red pixel', 'Blue pixel'], "
1076
+ "'itemsize': 4})")
1077
+
1078
+ def test_repr_structured_datetime(self):
1079
+ dt = np.dtype([('a', '<M8[D]'), ('b', '<m8[us]')])
1080
+ assert_equal(repr(dt),
1081
+ "dtype([('a', '<M8[D]'), ('b', '<m8[us]')])")
1082
+
1083
+ def test_repr_str_subarray(self):
1084
+ dt = np.dtype(('<i2', (1,)))
1085
+ assert_equal(repr(dt), "dtype(('<i2', (1,)))")
1086
+ assert_equal(str(dt), "('<i2', (1,))")
1087
+
1088
+ def test_base_dtype_with_object_type(self):
1089
+ # Issue gh-2798, should not error.
1090
+ np.array(['a'], dtype="O").astype(("O", [("name", "O")]))
1091
+
1092
+ def test_empty_string_to_object(self):
1093
+ # Pull request #4722
1094
+ np.array(["", ""]).astype(object)
1095
+
1096
+ def test_void_subclass_unsized(self):
1097
+ dt = np.dtype(np.record)
1098
+ assert_equal(repr(dt), "dtype('V')")
1099
+ assert_equal(str(dt), '|V0')
1100
+ assert_equal(dt.name, 'record')
1101
+
1102
+ def test_void_subclass_sized(self):
1103
+ dt = np.dtype((np.record, 2))
1104
+ assert_equal(repr(dt), "dtype('V2')")
1105
+ assert_equal(str(dt), '|V2')
1106
+ assert_equal(dt.name, 'record16')
1107
+
1108
+ def test_void_subclass_fields(self):
1109
+ dt = np.dtype((np.record, [('a', '<u2')]))
1110
+ assert_equal(repr(dt), "dtype((numpy.record, [('a', '<u2')]))")
1111
+ assert_equal(str(dt), "(numpy.record, [('a', '<u2')])")
1112
+ assert_equal(dt.name, 'record16')
1113
+
1114
+ def test_custom_dtype_str(self):
1115
+ dt = np.dtypes.StringDType()
1116
+ assert_equal(dt.str, "StringDType()")
1117
+
1118
+
1119
+ class TestDtypeAttributeDeletion:
1120
+
1121
+ def test_dtype_non_writable_attributes_deletion(self):
1122
+ dt = np.dtype(np.double)
1123
+ attr = ["subdtype", "descr", "str", "name", "base", "shape",
1124
+ "isbuiltin", "isnative", "isalignedstruct", "fields",
1125
+ "metadata", "hasobject"]
1126
+
1127
+ for s in attr:
1128
+ assert_raises(AttributeError, delattr, dt, s)
1129
+
1130
+ def test_dtype_writable_attributes_deletion(self):
1131
+ dt = np.dtype(np.double)
1132
+ attr = ["names"]
1133
+ for s in attr:
1134
+ assert_raises(AttributeError, delattr, dt, s)
1135
+
1136
+
1137
+ class TestDtypeAttributes:
1138
+ def test_descr_has_trailing_void(self):
1139
+ # see gh-6359
1140
+ dtype = np.dtype({
1141
+ 'names': ['A', 'B'],
1142
+ 'formats': ['f4', 'f4'],
1143
+ 'offsets': [0, 8],
1144
+ 'itemsize': 16})
1145
+ new_dtype = np.dtype(dtype.descr)
1146
+ assert_equal(new_dtype.itemsize, 16)
1147
+
1148
+ def test_name_dtype_subclass(self):
1149
+ # Ticket #4357
1150
+ class user_def_subcls(np.void):
1151
+ pass
1152
+ assert_equal(np.dtype(user_def_subcls).name, 'user_def_subcls')
1153
+
1154
+ def test_zero_stride(self):
1155
+ arr = np.ones(1, dtype="i8")
1156
+ arr = np.broadcast_to(arr, 10)
1157
+ assert arr.strides == (0,)
1158
+ with pytest.raises(ValueError):
1159
+ with warnings.catch_warnings(): # gh-28901
1160
+ warnings.filterwarnings(action="ignore",
1161
+ category=DeprecationWarning)
1162
+ arr.dtype = "i1"
1163
+
1164
+ class TestDTypeMakeCanonical:
1165
+ def check_canonical(self, dtype, canonical):
1166
+ """
1167
+ Check most properties relevant to "canonical" versions of a dtype,
1168
+ which is mainly native byte order for datatypes supporting this.
1169
+
1170
+ The main work is checking structured dtypes with fields, where we
1171
+ reproduce most the actual logic used in the C-code.
1172
+ """
1173
+ assert type(dtype) is type(canonical)
1174
+
1175
+ # a canonical DType should always have equivalent casting (both ways)
1176
+ assert np.can_cast(dtype, canonical, casting="equiv")
1177
+ assert np.can_cast(canonical, dtype, casting="equiv")
1178
+ # a canonical dtype (and its fields) is always native (checks fields):
1179
+ assert canonical.isnative
1180
+
1181
+ # Check that canonical of canonical is the same (no casting):
1182
+ assert np.result_type(canonical) == canonical
1183
+
1184
+ if not dtype.names:
1185
+ # The flags currently never change for unstructured dtypes
1186
+ assert dtype.flags == canonical.flags
1187
+ return
1188
+
1189
+ # Must have all the needs API flag set:
1190
+ assert dtype.flags & 0b10000
1191
+
1192
+ # Check that the fields are identical (including titles):
1193
+ assert dtype.fields.keys() == canonical.fields.keys()
1194
+
1195
+ def aligned_offset(offset, alignment):
1196
+ # round up offset:
1197
+ return - (-offset // alignment) * alignment
1198
+
1199
+ totalsize = 0
1200
+ max_alignment = 1
1201
+ for name in dtype.names:
1202
+ # each field is also canonical:
1203
+ new_field_descr = canonical.fields[name][0]
1204
+ self.check_canonical(dtype.fields[name][0], new_field_descr)
1205
+
1206
+ # Must have the "inherited" object related flags:
1207
+ expected = 0b11011 & new_field_descr.flags
1208
+ assert (canonical.flags & expected) == expected
1209
+
1210
+ if canonical.isalignedstruct:
1211
+ totalsize = aligned_offset(totalsize, new_field_descr.alignment)
1212
+ max_alignment = max(new_field_descr.alignment, max_alignment)
1213
+
1214
+ assert canonical.fields[name][1] == totalsize
1215
+ # if a title exists, they must match (otherwise empty tuple):
1216
+ assert dtype.fields[name][2:] == canonical.fields[name][2:]
1217
+
1218
+ totalsize += new_field_descr.itemsize
1219
+
1220
+ if canonical.isalignedstruct:
1221
+ totalsize = aligned_offset(totalsize, max_alignment)
1222
+ assert canonical.itemsize == totalsize
1223
+ assert canonical.alignment == max_alignment
1224
+
1225
+ def test_simple(self):
1226
+ dt = np.dtype(">i4")
1227
+ assert np.result_type(dt).isnative
1228
+ assert np.result_type(dt).num == dt.num
1229
+
1230
+ # dtype with empty space:
1231
+ struct_dt = np.dtype(">i4,<i1,i8,V3")[["f0", "f2"]]
1232
+ canonical = np.result_type(struct_dt)
1233
+ assert canonical.itemsize == 4 + 8
1234
+ assert canonical.isnative
1235
+
1236
+ # aligned struct dtype with empty space:
1237
+ struct_dt = np.dtype(">i1,<i4,i8,V3", align=True)[["f0", "f2"]]
1238
+ canonical = np.result_type(struct_dt)
1239
+ assert canonical.isalignedstruct
1240
+ assert canonical.itemsize == np.dtype("i8").alignment + 8
1241
+ assert canonical.isnative
1242
+
1243
+ def test_object_flag_not_inherited(self):
1244
+ # The following dtype still indicates "object", because its included
1245
+ # in the inaccessible space (maybe this could change at some point):
1246
+ arr = np.ones(3, "i,O,i")[["f0", "f2"]]
1247
+ assert arr.dtype.hasobject
1248
+ canonical_dt = np.result_type(arr.dtype)
1249
+ assert not canonical_dt.hasobject
1250
+
1251
+ @pytest.mark.slow
1252
+ @hypothesis.given(dtype=hynp.nested_dtypes())
1253
+ def test_make_canonical_hypothesis(self, dtype):
1254
+ canonical = np.result_type(dtype)
1255
+ self.check_canonical(dtype, canonical)
1256
+ # result_type with two arguments should always give identical results:
1257
+ two_arg_result = np.result_type(dtype, dtype)
1258
+ assert np.can_cast(two_arg_result, canonical, casting="no")
1259
+
1260
+ @pytest.mark.slow
1261
+ @hypothesis.given(
1262
+ dtype=hypothesis.extra.numpy.array_dtypes(
1263
+ subtype_strategy=hypothesis.extra.numpy.array_dtypes(),
1264
+ min_size=5, max_size=10, allow_subarrays=True),
1265
+ random=hypothesis.strategies.randoms())
1266
+ def test_structured(self, dtype, random):
1267
+ # Pick 4 of the fields at random. This will leave empty space in the
1268
+ # dtype (since we do not canonicalize it here).
1269
+ field_subset = random.sample(dtype.names, k=4)
1270
+ dtype_with_empty_space = dtype[field_subset]
1271
+ assert dtype_with_empty_space.itemsize == dtype.itemsize
1272
+ canonicalized = np.result_type(dtype_with_empty_space)
1273
+ self.check_canonical(dtype_with_empty_space, canonicalized)
1274
+ # promotion with two arguments should always give identical results:
1275
+ two_arg_result = np.promote_types(
1276
+ dtype_with_empty_space, dtype_with_empty_space)
1277
+ assert np.can_cast(two_arg_result, canonicalized, casting="no")
1278
+
1279
+ # Ensure that we also check aligned struct (check the opposite, in
1280
+ # case hypothesis grows support for `align`. Then repeat the test:
1281
+ dtype_aligned = np.dtype(dtype.descr, align=not dtype.isalignedstruct)
1282
+ dtype_with_empty_space = dtype_aligned[field_subset]
1283
+ assert dtype_with_empty_space.itemsize == dtype_aligned.itemsize
1284
+ canonicalized = np.result_type(dtype_with_empty_space)
1285
+ self.check_canonical(dtype_with_empty_space, canonicalized)
1286
+ # promotion with two arguments should always give identical results:
1287
+ two_arg_result = np.promote_types(
1288
+ dtype_with_empty_space, dtype_with_empty_space)
1289
+ assert np.can_cast(two_arg_result, canonicalized, casting="no")
1290
+
1291
+
1292
+ class TestPickling:
1293
+
1294
+ def check_pickling(self, dtype):
1295
+ for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1296
+ buf = pickle.dumps(dtype, proto)
1297
+ # The dtype pickling itself pickles `np.dtype` if it is pickled
1298
+ # as a singleton `dtype` should be stored in the buffer:
1299
+ assert b"_DType_reconstruct" not in buf
1300
+ assert b"dtype" in buf
1301
+ pickled = pickle.loads(buf)
1302
+ assert_equal(pickled, dtype)
1303
+ assert_equal(pickled.descr, dtype.descr)
1304
+ if dtype.metadata is not None:
1305
+ assert_equal(pickled.metadata, dtype.metadata)
1306
+ # Check the reconstructed dtype is functional
1307
+ x = np.zeros(3, dtype=dtype)
1308
+ y = np.zeros(3, dtype=pickled)
1309
+ assert_equal(x, y)
1310
+ assert_equal(x[0], y[0])
1311
+
1312
+ @pytest.mark.skipif(not IS_64BIT, reason="test requires 64-bit system")
1313
+ @pytest.mark.xfail(reason="dtype conversion doesn't allow this yet.")
1314
+ def test_pickling_large(self):
1315
+ # The actual itemsize is larger than a c-integer here.
1316
+ dtype = np.dtype(f"({2**31},)i")
1317
+ self.check_pickling(dtype)
1318
+ dtype = np.dtype(f"({2**31},)i", metadata={"a": "b"})
1319
+ self.check_pickling(dtype)
1320
+
1321
+ @pytest.mark.parametrize('t', [int, float, complex, np.int32, str, object,
1322
+ bool])
1323
+ def test_builtin(self, t):
1324
+ self.check_pickling(np.dtype(t))
1325
+
1326
+ def test_structured(self):
1327
+ dt = np.dtype(([('a', '>f4', (2, 1)), ('b', '<f8', (1, 3))], (2, 2)))
1328
+ self.check_pickling(dt)
1329
+
1330
+ def test_structured_aligned(self):
1331
+ dt = np.dtype('i4, i1', align=True)
1332
+ self.check_pickling(dt)
1333
+
1334
+ def test_structured_unaligned(self):
1335
+ dt = np.dtype('i4, i1', align=False)
1336
+ self.check_pickling(dt)
1337
+
1338
+ def test_structured_padded(self):
1339
+ dt = np.dtype({
1340
+ 'names': ['A', 'B'],
1341
+ 'formats': ['f4', 'f4'],
1342
+ 'offsets': [0, 8],
1343
+ 'itemsize': 16})
1344
+ self.check_pickling(dt)
1345
+
1346
+ def test_structured_titles(self):
1347
+ dt = np.dtype({'names': ['r', 'b'],
1348
+ 'formats': ['u1', 'u1'],
1349
+ 'titles': ['Red pixel', 'Blue pixel']})
1350
+ self.check_pickling(dt)
1351
+
1352
+ @pytest.mark.parametrize('base', ['m8', 'M8'])
1353
+ @pytest.mark.parametrize('unit', ['', 'Y', 'M', 'W', 'D', 'h', 'm', 's',
1354
+ 'ms', 'us', 'ns', 'ps', 'fs', 'as'])
1355
+ def test_datetime(self, base, unit):
1356
+ dt = np.dtype(f'{base}[{unit}]' if unit else base)
1357
+ self.check_pickling(dt)
1358
+ if unit:
1359
+ dt = np.dtype(f'{base}[7{unit}]')
1360
+ self.check_pickling(dt)
1361
+
1362
+ def test_metadata(self):
1363
+ dt = np.dtype(int, metadata={'datum': 1})
1364
+ self.check_pickling(dt)
1365
+
1366
+ @pytest.mark.parametrize("DType",
1367
+ [type(np.dtype(t)) for t in np.typecodes['All']] +
1368
+ [type(np.dtype(rational)), type(np.dtype(rational2)), np.dtype])
1369
+ def test_pickle_dtype_class(self, DType):
1370
+ # Check that DTypes (the classes/types) roundtrip when pickling
1371
+ for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1372
+ roundtrip_DType = pickle.loads(pickle.dumps(DType, proto))
1373
+ assert roundtrip_DType is DType
1374
+
1375
+ @pytest.mark.parametrize("dt",
1376
+ [np.dtype(t) for t in np.typecodes['All']] +
1377
+ [np.dtype(rational), np.dtype(rational2)])
1378
+ def test_pickle_dtype(self, dt):
1379
+ # Check that dtype instances roundtrip when pickling and that pickling
1380
+ # doesn't change the hash value
1381
+ pre_pickle_hash = hash(dt)
1382
+ for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1383
+ roundtrip_dt = pickle.loads(pickle.dumps(dt, proto))
1384
+ assert roundtrip_dt == dt
1385
+ assert hash(roundtrip_dt) == pre_pickle_hash
1386
+
1387
+ @pytest.mark.parametrize('dt', [
1388
+ np.dtype([('a', 'i4'), ('b', 'f8')]),
1389
+ np.dtype('i4, i1', align=True),
1390
+ ])
1391
+ def test_setstate_invalid_tuple_size(self, dt):
1392
+ # gh-30476
1393
+ valid_state = dt.__reduce__()[2]
1394
+ dt.__setstate__(valid_state)
1395
+
1396
+ for size in [1, 2, 3, 4]:
1397
+ with pytest.raises(
1398
+ ValueError, match="Invalid state while unpickling"
1399
+ ):
1400
+ dt.__setstate__(valid_state[:size])
1401
+
1402
+ min_extra = 10 - len(valid_state)
1403
+ for extra in range(min_extra, min_extra + 5):
1404
+ extended = valid_state + (None,) * extra
1405
+ with pytest.raises(
1406
+ ValueError, match="Invalid state while unpickling"
1407
+ ):
1408
+ dt.__setstate__(extended)
1409
+
1410
+
1411
+ class TestPromotion:
1412
+ """Test cases related to more complex DType promotions. Further promotion
1413
+ tests are defined in `test_numeric.py`
1414
+ """
1415
+ @pytest.mark.parametrize(["other", "expected"],
1416
+ [(2**16 - 1, np.complex64),
1417
+ (2**32 - 1, np.complex64),
1418
+ (np.float16(2), np.complex64),
1419
+ (np.float32(2), np.complex64),
1420
+ (np.longdouble(2), np.clongdouble),
1421
+ # Base of the double value to sidestep any rounding issues:
1422
+ (np.longdouble(np.nextafter(1.7e308, 0.)), np.clongdouble),
1423
+ # Additionally use "nextafter" so the cast can't round down:
1424
+ (np.longdouble(np.nextafter(1.7e308, np.inf)), np.clongdouble),
1425
+ # repeat for complex scalars:
1426
+ (np.complex64(2), np.complex64),
1427
+ (np.clongdouble(2), np.clongdouble),
1428
+ # Base of the double value to sidestep any rounding issues:
1429
+ (np.clongdouble(np.nextafter(1.7e308, 0.) * 1j), np.clongdouble),
1430
+ # Additionally use "nextafter" so the cast can't round down:
1431
+ (np.clongdouble(np.nextafter(1.7e308, np.inf)), np.clongdouble),
1432
+ ])
1433
+ def test_complex_other_value_based(self, other, expected):
1434
+ # This would change if we modify the value based promotion
1435
+ min_complex = np.dtype(np.complex64)
1436
+
1437
+ res = np.result_type(other, min_complex)
1438
+ assert res == expected
1439
+ # Check the same for a simple ufunc call that uses the same logic:
1440
+ res = np.minimum(other, np.ones(3, dtype=min_complex)).dtype
1441
+ assert res == expected
1442
+
1443
+ @pytest.mark.parametrize(["other", "expected"],
1444
+ [(np.bool, np.complex128),
1445
+ (np.int64, np.complex128),
1446
+ (np.float16, np.complex64),
1447
+ (np.float32, np.complex64),
1448
+ (np.float64, np.complex128),
1449
+ (np.longdouble, np.clongdouble),
1450
+ (np.complex64, np.complex64),
1451
+ (np.complex128, np.complex128),
1452
+ (np.clongdouble, np.clongdouble),
1453
+ ])
1454
+ def test_complex_scalar_value_based(self, other, expected):
1455
+ # This would change if we modify the value based promotion
1456
+ complex_scalar = 1j
1457
+
1458
+ res = np.result_type(other, complex_scalar)
1459
+ assert res == expected
1460
+ # Check the same for a simple ufunc call that uses the same logic:
1461
+ res = np.minimum(np.ones(3, dtype=other), complex_scalar).dtype
1462
+ assert res == expected
1463
+
1464
+ @pytest.mark.parametrize("rat_cls", [rational, rational2])
1465
+ def test_complex_pyscalar_promote_rational(self, rat_cls):
1466
+ with pytest.raises(TypeError,
1467
+ match=r".* no common DType exists for the given inputs"):
1468
+ np.result_type(1j, rat_cls)
1469
+
1470
+ with pytest.raises(TypeError,
1471
+ match=r".* no common DType exists for the given inputs"):
1472
+ np.result_type(1j, rat_cls(1, 2))
1473
+
1474
+ @pytest.mark.parametrize("val", [2, 2**32, 2**63, 2**64, 2 * 100])
1475
+ def test_python_integer_promotion(self, val):
1476
+ # If we only pass scalars (mainly python ones!), NEP 50 means
1477
+ # that we get the default integer
1478
+ expected_dtype = np.dtype(int) # the default integer
1479
+ assert np.result_type(val, 0) == expected_dtype
1480
+ # With NEP 50, the NumPy scalar wins though:
1481
+ assert np.result_type(val, np.int8(0)) == np.int8
1482
+
1483
+ @pytest.mark.parametrize(["other", "expected"],
1484
+ [(1, rational), (1., np.float64)])
1485
+ def test_float_int_pyscalar_promote_rational(self, other, expected):
1486
+ # Note that rationals are a bit awkward as they promote with float64
1487
+ # or default ints, but not float16 or uint8/int8 (which looks
1488
+ # inconsistent here). The new promotion fixed this (partially?)
1489
+ assert np.result_type(other, rational) == expected
1490
+ assert np.result_type(other, rational(1, 2)) == expected
1491
+
1492
+ @pytest.mark.parametrize(["dtypes", "expected"], [
1493
+ # These promotions are not associative/commutative:
1494
+ ([np.uint16, np.int16, np.float16], np.float32),
1495
+ ([np.uint16, np.int8, np.float16], np.float32),
1496
+ ([np.uint8, np.int16, np.float16], np.float32),
1497
+ # The following promotions are not ambiguous, but cover code
1498
+ # paths of abstract promotion (no particular logic being tested)
1499
+ ([1, 1, np.float64], np.float64),
1500
+ ([1, 1., np.complex128], np.complex128),
1501
+ ([1, 1j, np.float64], np.complex128),
1502
+ ([1., 1., np.int64], np.float64),
1503
+ ([1., 1j, np.float64], np.complex128),
1504
+ ([1j, 1j, np.float64], np.complex128),
1505
+ ([1, True, np.bool], np.int_),
1506
+ ])
1507
+ def test_permutations_do_not_influence_result(self, dtypes, expected):
1508
+ # Tests that most permutations do not influence the result. In the
1509
+ # above some uint and int combinations promote to a larger integer
1510
+ # type, which would then promote to a larger than necessary float.
1511
+ for perm in permutations(dtypes):
1512
+ assert np.result_type(*perm) == expected
1513
+
1514
+
1515
+ def test_rational2_uses_new_dtype_api():
1516
+ # ``rational2`` provides its own ``common_dtype`` slot (which the
1517
+ # legacy ``rational`` cannot), and that slot rejects floats.
1518
+ assert np.result_type(rational, 1.0) == np.float64
1519
+ with pytest.raises(TypeError,
1520
+ match=r".* no common DType exists for the given inputs"):
1521
+ np.result_type(rational2, 1.0)
1522
+
1523
+
1524
+ @pytest.mark.parametrize("rat_cls", [rational, rational2])
1525
+ def test_rational_dtype(rat_cls):
1526
+ # test for bug gh-5719
1527
+ a = np.array([1111], dtype=rat_cls).astype
1528
+ assert_raises(OverflowError, a, 'int8')
1529
+
1530
+ # test that dtype detection finds user-defined types
1531
+ x = rat_cls(1)
1532
+ assert np.array([x, x]).dtype.type is rat_cls
1533
+
1534
+
1535
+ def test_dtypes_are_true():
1536
+ # test for gh-6294
1537
+ assert bool(np.dtype('f8'))
1538
+ assert bool(np.dtype('i8'))
1539
+ assert bool(np.dtype([('a', 'i8'), ('b', 'f4')]))
1540
+
1541
+
1542
+ def test_invalid_dtype_string():
1543
+ # test for gh-10440
1544
+ assert_raises(TypeError, np.dtype, 'f8,i8,[f8,i8]')
1545
+ assert_raises(TypeError, np.dtype, 'Fl\xfcgel')
1546
+
1547
+
1548
+ def test_keyword_argument():
1549
+ # test for https://github.com/numpy/numpy/pull/16574#issuecomment-642660971
1550
+ assert np.dtype(dtype=np.float64) == np.dtype(np.float64)
1551
+
1552
+
1553
+ class TestFromDTypeAttribute:
1554
+ def test_simple(self):
1555
+ class dt:
1556
+ dtype = np.dtype("f8")
1557
+
1558
+ assert np.dtype(dt) == np.float64
1559
+ assert np.dtype(dt()) == np.float64
1560
+
1561
+ def test_recursive(self):
1562
+ # This used to recurse. It now doesn't, we enforce the
1563
+ # dtype attribute to be a dtype (and will not recurse).
1564
+ class dt:
1565
+ pass
1566
+
1567
+ dt.dtype = dt
1568
+ with pytest.raises(ValueError):
1569
+ np.dtype(dt)
1570
+
1571
+ dt_instance = dt()
1572
+ dt_instance.dtype = dt
1573
+ with pytest.raises(ValueError):
1574
+ np.dtype(dt_instance)
1575
+
1576
+ @pytest.mark.xfail("LSAN_OPTIONS" in os.environ, reason="known leak", run=False)
1577
+ def test_void_subtype(self):
1578
+ class dt(np.void):
1579
+ # This code path is fully untested before, so it is unclear
1580
+ # what this should be useful for. Note that if np.void is used
1581
+ # numpy will think we are deallocating a base type [1.17, 2019-02].
1582
+ dtype = np.dtype("f,f")
1583
+
1584
+ np.dtype(dt)
1585
+ np.dtype(dt(1))
1586
+
1587
+ def test_void_subtype_recursive(self):
1588
+ # Used to recurse, but dtype is now enforced to be a dtype instance
1589
+ # so that we do not recurse.
1590
+ class vdt(np.void):
1591
+ pass
1592
+
1593
+ vdt.dtype = vdt
1594
+
1595
+ with pytest.raises(ValueError):
1596
+ np.dtype(vdt)
1597
+
1598
+ with pytest.raises(ValueError):
1599
+ np.dtype(vdt(1))
1600
+
1601
+
1602
+ class TestFromDTypeProtocol:
1603
+ def test_simple(self):
1604
+ class A:
1605
+ dtype = np.dtype("f8")
1606
+
1607
+ assert np.dtype(A()) == np.dtype(np.float64)
1608
+
1609
+ def test_not_a_dtype(self):
1610
+ # This also prevents coercion as a trivial path, although
1611
+ # a custom error may be nicer.
1612
+ class ArrayLike:
1613
+ __numpy_dtype__ = None
1614
+ dtype = np.dtype("f8")
1615
+
1616
+ with pytest.raises(ValueError, match=".*__numpy_dtype__.*"):
1617
+ np.dtype(ArrayLike())
1618
+
1619
+ def test_prevent_dtype_explicit(self):
1620
+ class ArrayLike:
1621
+ @property
1622
+ def __numpy_dtype__(self):
1623
+ raise RuntimeError("my error!")
1624
+
1625
+ with pytest.raises(RuntimeError, match="my error!"):
1626
+ np.dtype(ArrayLike())
1627
+
1628
+ def test_type_object(self):
1629
+ class TypeWithProperty:
1630
+ @property
1631
+ def __numpy_dtype__(self):
1632
+ raise RuntimeError("not reached")
1633
+
1634
+ # Arbitrary types go to object currently, and the
1635
+ # protocol doesn't prevent that.
1636
+ assert np.dtype(TypeWithProperty) == object
1637
+
1638
+
1639
+ class TestDTypeClasses:
1640
+ @pytest.mark.parametrize(
1641
+ "dtype", list(np.typecodes['All']) + [rational, rational2])
1642
+ def test_basic_dtypes_subclass_properties(self, dtype):
1643
+ # Note: Except for the isinstance and type checks, these attributes
1644
+ # are considered currently private and may change.
1645
+ dtype = np.dtype(dtype)
1646
+ assert isinstance(dtype, np.dtype)
1647
+ assert type(dtype) is not np.dtype
1648
+ if dtype.type.__name__ not in ("rational", "rational2"):
1649
+ dt_name = type(dtype).__name__.lower().removesuffix("dtype")
1650
+ if dt_name in {"uint", "int"}:
1651
+ # The scalar names has a `c` attached because "int" is Python
1652
+ # int and that is long...
1653
+ dt_name += "c"
1654
+ sc_name = dtype.type.__name__
1655
+ assert dt_name == sc_name.strip("_")
1656
+ assert type(dtype).__module__ == "numpy.dtypes"
1657
+
1658
+ assert getattr(numpy.dtypes, type(dtype).__name__) is type(dtype)
1659
+ elif dtype.type.__name__ == "rational":
1660
+ assert type(dtype).__name__ == "dtype[rational]"
1661
+ assert type(dtype).__module__ == "numpy"
1662
+
1663
+ assert not type(dtype)._abstract
1664
+
1665
+ # the flexible dtypes and datetime/timedelta have additional parameters
1666
+ # which are more than just storage information, these would need to be
1667
+ # given when creating a dtype:
1668
+ parametric = (np.void, np.str_, np.bytes_, np.datetime64, np.timedelta64)
1669
+ if dtype.type not in parametric:
1670
+ assert not type(dtype)._parametric
1671
+ assert type(dtype)() is dtype
1672
+ else:
1673
+ assert type(dtype)._parametric
1674
+ with assert_raises(TypeError):
1675
+ type(dtype)()
1676
+
1677
+ def test_dtype_superclass(self):
1678
+ assert type(np.dtype) is not type
1679
+ assert isinstance(np.dtype, type)
1680
+
1681
+ assert type(np.dtype).__name__ == "_DTypeMeta"
1682
+ assert type(np.dtype).__module__ == "numpy"
1683
+ assert np.dtype._abstract
1684
+
1685
+ def test_is_numeric(self):
1686
+ all_codes = set(np.typecodes['All'])
1687
+ numeric_codes = set(np.typecodes['AllInteger'] +
1688
+ np.typecodes['AllFloat'] + '?')
1689
+ non_numeric_codes = all_codes - numeric_codes
1690
+
1691
+ for code in numeric_codes:
1692
+ assert type(np.dtype(code))._is_numeric
1693
+
1694
+ for code in non_numeric_codes:
1695
+ assert not type(np.dtype(code))._is_numeric
1696
+
1697
+ @pytest.mark.parametrize("int_", ["UInt", "Int"])
1698
+ @pytest.mark.parametrize("size", [8, 16, 32, 64])
1699
+ def test_integer_alias_names(self, int_, size):
1700
+ DType = getattr(numpy.dtypes, f"{int_}{size}DType")
1701
+ sctype = getattr(numpy, f"{int_.lower()}{size}")
1702
+ assert DType.type is sctype
1703
+ assert DType.__name__.lower().removesuffix("dtype") == sctype.__name__
1704
+
1705
+ @pytest.mark.parametrize("name",
1706
+ ["Half", "Float", "Double", "CFloat", "CDouble"])
1707
+ def test_float_alias_names_not_present(self, name):
1708
+ assert not hasattr(numpy.dtypes, f"{name}DType")
1709
+
1710
+ def test_scalar_helper_all_dtypes(self):
1711
+ for dtype in np.dtypes.__all__:
1712
+ if dtype == "register_dlpack_dtype":
1713
+ continue
1714
+
1715
+ dt_class = getattr(np.dtypes, dtype)
1716
+ dt = np.dtype(dt_class)
1717
+ if dt.char not in 'OTVM':
1718
+ assert np._core.multiarray.scalar(dt) == dt.type()
1719
+ elif dt.char == 'V':
1720
+ assert np._core.multiarray.scalar(dt) == dt.type(b'\x00')
1721
+ elif dt.char == 'M':
1722
+ # can't do anything with this without generating ValueError
1723
+ # because 'M' has no units
1724
+ _ = np._core.multiarray.scalar(dt)
1725
+ else:
1726
+ with pytest.raises(TypeError):
1727
+ np._core.multiarray.scalar(dt)
1728
+
1729
+
1730
+ class TestFromCTypes:
1731
+
1732
+ @staticmethod
1733
+ def check(ctype, dtype):
1734
+ dtype = np.dtype(dtype)
1735
+ assert np.dtype(ctype) == dtype
1736
+ assert np.dtype(ctype()) == dtype
1737
+ assert ctypes.sizeof(ctype) == dtype.itemsize
1738
+
1739
+ def test_array(self):
1740
+ c8 = ctypes.c_uint8
1741
+ self.check( 3 * c8, (np.uint8, (3,)))
1742
+ self.check( 1 * c8, (np.uint8, (1,)))
1743
+ self.check( 0 * c8, (np.uint8, (0,)))
1744
+ self.check(1 * (3 * c8), ((np.uint8, (3,)), (1,)))
1745
+ self.check(3 * (1 * c8), ((np.uint8, (1,)), (3,)))
1746
+
1747
+ def test_padded_structure(self):
1748
+ class PaddedStruct(ctypes.Structure):
1749
+ _fields_ = [
1750
+ ('a', ctypes.c_uint8),
1751
+ ('b', ctypes.c_uint16)
1752
+ ]
1753
+ expected = np.dtype([
1754
+ ('a', np.uint8),
1755
+ ('b', np.uint16)
1756
+ ], align=True)
1757
+ self.check(PaddedStruct, expected)
1758
+
1759
+ def test_bit_fields(self):
1760
+ class BitfieldStruct(ctypes.Structure):
1761
+ _fields_ = [
1762
+ ('a', ctypes.c_uint8, 7),
1763
+ ('b', ctypes.c_uint8, 1)
1764
+ ]
1765
+ assert_raises(TypeError, np.dtype, BitfieldStruct)
1766
+ assert_raises(TypeError, np.dtype, BitfieldStruct())
1767
+
1768
+ def test_pointer(self):
1769
+ p_uint8 = ctypes.POINTER(ctypes.c_uint8)
1770
+ assert_raises(TypeError, np.dtype, p_uint8)
1771
+
1772
+ def test_size_t(self):
1773
+ assert np.dtype(np.uintp) is np.dtype("N")
1774
+ self.check(ctypes.c_size_t, np.uintp)
1775
+
1776
+ def test_void_pointer(self):
1777
+ self.check(ctypes.c_void_p, "P")
1778
+
1779
+ def test_union(self):
1780
+ class Union(ctypes.Union):
1781
+ _fields_ = [
1782
+ ('a', ctypes.c_uint8),
1783
+ ('b', ctypes.c_uint16),
1784
+ ]
1785
+ expected = np.dtype({
1786
+ "names": ['a', 'b'],
1787
+ "formats": [np.uint8, np.uint16],
1788
+ "offsets": [0, 0],
1789
+ "itemsize": 2
1790
+ })
1791
+ self.check(Union, expected)
1792
+
1793
+ def test_union_with_struct_packed(self):
1794
+ class Struct(ctypes.Structure):
1795
+ _pack_ = 1
1796
+ _fields_ = [
1797
+ ('one', ctypes.c_uint8),
1798
+ ('two', ctypes.c_uint32)
1799
+ ]
1800
+
1801
+ class Union(ctypes.Union):
1802
+ _fields_ = [
1803
+ ('a', ctypes.c_uint8),
1804
+ ('b', ctypes.c_uint16),
1805
+ ('c', ctypes.c_uint32),
1806
+ ('d', Struct),
1807
+ ]
1808
+ expected = np.dtype({
1809
+ "names": ['a', 'b', 'c', 'd'],
1810
+ "formats": [
1811
+ 'u1',
1812
+ np.uint16,
1813
+ np.uint32,
1814
+ [('one', 'u1'), ('two', np.uint32)],
1815
+ ],
1816
+ "offsets": [0, 0, 0, 0],
1817
+ "itemsize": ctypes.sizeof(Union)
1818
+ })
1819
+ self.check(Union, expected)
1820
+
1821
+ def test_union_packed(self):
1822
+ class Struct(ctypes.Structure):
1823
+ _fields_ = [
1824
+ ('one', ctypes.c_uint8),
1825
+ ('two', ctypes.c_uint32)
1826
+ ]
1827
+ _pack_ = 1
1828
+
1829
+ class Union(ctypes.Union):
1830
+ _pack_ = 1
1831
+ _fields_ = [
1832
+ ('a', ctypes.c_uint8),
1833
+ ('b', ctypes.c_uint16),
1834
+ ('c', ctypes.c_uint32),
1835
+ ('d', Struct),
1836
+ ]
1837
+ expected = np.dtype({
1838
+ "names": ['a', 'b', 'c', 'd'],
1839
+ "formats": [
1840
+ 'u1',
1841
+ np.uint16,
1842
+ np.uint32,
1843
+ [('one', 'u1'), ('two', np.uint32)],
1844
+ ],
1845
+ "offsets": [0, 0, 0, 0],
1846
+ "itemsize": ctypes.sizeof(Union)
1847
+ })
1848
+ self.check(Union, expected)
1849
+
1850
+ def test_packed_structure(self):
1851
+ class PackedStructure(ctypes.Structure):
1852
+ _pack_ = 1
1853
+ _fields_ = [
1854
+ ('a', ctypes.c_uint8),
1855
+ ('b', ctypes.c_uint16)
1856
+ ]
1857
+ expected = np.dtype([
1858
+ ('a', np.uint8),
1859
+ ('b', np.uint16)
1860
+ ])
1861
+ self.check(PackedStructure, expected)
1862
+
1863
+ def test_large_packed_structure(self):
1864
+ class PackedStructure(ctypes.Structure):
1865
+ _pack_ = 2
1866
+ _fields_ = [
1867
+ ('a', ctypes.c_uint8),
1868
+ ('b', ctypes.c_uint16),
1869
+ ('c', ctypes.c_uint8),
1870
+ ('d', ctypes.c_uint16),
1871
+ ('e', ctypes.c_uint32),
1872
+ ('f', ctypes.c_uint32),
1873
+ ('g', ctypes.c_uint8)
1874
+ ]
1875
+ expected = np.dtype({
1876
+ "formats": [
1877
+ np.uint8,
1878
+ np.uint16,
1879
+ np.uint8,
1880
+ np.uint16,
1881
+ np.uint32,
1882
+ np.uint32,
1883
+ np.uint8,
1884
+ ],
1885
+ "offsets": [0, 2, 4, 6, 8, 12, 16],
1886
+ "names": ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
1887
+ "itemsize": 18})
1888
+ self.check(PackedStructure, expected)
1889
+
1890
+ def test_big_endian_structure_packed(self):
1891
+ class BigEndStruct(ctypes.BigEndianStructure):
1892
+ _fields_ = [
1893
+ ('one', ctypes.c_uint8),
1894
+ ('two', ctypes.c_uint32)
1895
+ ]
1896
+ _pack_ = 1
1897
+ expected = np.dtype([('one', 'u1'), ('two', '>u4')])
1898
+ self.check(BigEndStruct, expected)
1899
+
1900
+ def test_little_endian_structure_packed(self):
1901
+ class LittleEndStruct(ctypes.LittleEndianStructure):
1902
+ _fields_ = [
1903
+ ('one', ctypes.c_uint8),
1904
+ ('two', ctypes.c_uint32)
1905
+ ]
1906
+ _pack_ = 1
1907
+ expected = np.dtype([('one', 'u1'), ('two', '<u4')])
1908
+ self.check(LittleEndStruct, expected)
1909
+
1910
+ def test_little_endian_structure(self):
1911
+ class PaddedStruct(ctypes.LittleEndianStructure):
1912
+ _fields_ = [
1913
+ ('a', ctypes.c_uint8),
1914
+ ('b', ctypes.c_uint16)
1915
+ ]
1916
+ expected = np.dtype([
1917
+ ('a', '<B'),
1918
+ ('b', '<H')
1919
+ ], align=True)
1920
+ self.check(PaddedStruct, expected)
1921
+
1922
+ def test_big_endian_structure(self):
1923
+ class PaddedStruct(ctypes.BigEndianStructure):
1924
+ _fields_ = [
1925
+ ('a', ctypes.c_uint8),
1926
+ ('b', ctypes.c_uint16)
1927
+ ]
1928
+ expected = np.dtype([
1929
+ ('a', '>B'),
1930
+ ('b', '>H')
1931
+ ], align=True)
1932
+ self.check(PaddedStruct, expected)
1933
+
1934
+ def test_simple_endian_types(self):
1935
+ self.check(ctypes.c_uint16.__ctype_le__, np.dtype('<u2'))
1936
+ self.check(ctypes.c_uint16.__ctype_be__, np.dtype('>u2'))
1937
+ self.check(ctypes.c_uint8.__ctype_le__, np.dtype('u1'))
1938
+ self.check(ctypes.c_uint8.__ctype_be__, np.dtype('u1'))
1939
+
1940
+ all_types = set(np.typecodes['All'])
1941
+ all_pairs = list(permutations(all_types, 2))
1942
+
1943
+ @pytest.mark.parametrize("pair", all_pairs)
1944
+ def test_pairs(self, pair):
1945
+ """
1946
+ Check that np.dtype('x,y') matches [np.dtype('x'), np.dtype('y')]
1947
+ Example: np.dtype('d,I') -> dtype([('f0', '<f8'), ('f1', '<u4')])
1948
+ """
1949
+ # gh-5645: check that np.dtype('i,L') can be used
1950
+ pair_type = np.dtype('{},{}'.format(*pair))
1951
+ expected = np.dtype([('f0', pair[0]), ('f1', pair[1])])
1952
+ assert_equal(pair_type, expected)
1953
+
1954
+
1955
+ class TestUserDType:
1956
+ @pytest.mark.leaks_references(reason="dynamically creates custom dtype.")
1957
+ @pytest.mark.thread_unsafe(
1958
+ reason="crashes when GIL disabled, dtype setup is thread-unsafe",
1959
+ )
1960
+ @pytest.mark.xfail("LSAN_OPTIONS" in os.environ, reason="known leak", run=False)
1961
+ def test_custom_structured_dtype(self):
1962
+ class mytype:
1963
+ pass
1964
+
1965
+ blueprint = np.dtype([("field", object)])
1966
+ dt = create_custom_field_dtype(blueprint, mytype, 0)
1967
+ assert dt.type == mytype
1968
+ # We cannot (currently) *create* this dtype with `np.dtype` because
1969
+ # mytype does not inherit from `np.generic`. This seems like an
1970
+ # unnecessary restriction, but one that has been around forever:
1971
+ assert np.dtype(mytype) == np.dtype("O")
1972
+
1973
+ if HAS_REFCOUNT:
1974
+ # Create an array and test that memory gets cleaned up (gh-25949)
1975
+ o = object()
1976
+ startcount = sys.getrefcount(o)
1977
+ a = np.array([o], dtype=dt)
1978
+ del a
1979
+ assert sys.getrefcount(o) == startcount
1980
+
1981
+ @pytest.mark.thread_unsafe(
1982
+ reason="crashes when GIL disabled, dtype setup is thread-unsafe",
1983
+ )
1984
+ @pytest.mark.xfail("LSAN_OPTIONS" in os.environ, reason="known leak", run=False)
1985
+ def test_custom_structured_dtype_errors(self):
1986
+ class mytype:
1987
+ pass
1988
+
1989
+ blueprint = np.dtype([("field", object)])
1990
+
1991
+ with pytest.raises(ValueError):
1992
+ # Tests what happens if fields are unset during creation
1993
+ # which is currently rejected due to the containing object
1994
+ # (see PyArray_RegisterDataType).
1995
+ create_custom_field_dtype(blueprint, mytype, 1)
1996
+
1997
+ with pytest.raises(RuntimeError):
1998
+ # Tests that a dtype must have its type field set up to np.dtype
1999
+ # or in this case a builtin instance.
2000
+ create_custom_field_dtype(blueprint, mytype, 2)
2001
+
2002
+
2003
+ class TestClassGetItem:
2004
+ def test_dtype(self) -> None:
2005
+ alias = np.dtype[Any]
2006
+ assert isinstance(alias, types.GenericAlias)
2007
+ assert alias.__origin__ is np.dtype
2008
+
2009
+ @pytest.mark.parametrize("code", np.typecodes["All"])
2010
+ def test_dtype_subclass(self, code: str) -> None:
2011
+ cls = type(np.dtype(code))
2012
+ alias = cls[Any]
2013
+ assert isinstance(alias, types.GenericAlias)
2014
+ assert alias.__origin__ is cls
2015
+
2016
+ @pytest.mark.parametrize("arg_len", range(4))
2017
+ def test_subscript_tuple(self, arg_len: int) -> None:
2018
+ arg_tup = (Any,) * arg_len
2019
+ if arg_len == 1:
2020
+ assert np.dtype[arg_tup]
2021
+ else:
2022
+ with pytest.raises(TypeError):
2023
+ np.dtype[arg_tup]
2024
+
2025
+ def test_subscript_scalar(self) -> None:
2026
+ assert np.dtype[Any]
2027
+
2028
+
2029
+ def test_result_type_integers_and_unitless_timedelta64():
2030
+ # Regression test for gh-20077. The following call of `result_type`
2031
+ # would cause a seg. fault.
2032
+ with pytest.warns(
2033
+ DeprecationWarning,
2034
+ match="The 'generic' unit for NumPy timedelta is deprecated",
2035
+ ):
2036
+ td = np.timedelta64(4)
2037
+ result = np.result_type(0, td)
2038
+ assert_dtype_equal(result, td.dtype)
2039
+
2040
+
2041
+ def test_creating_dtype_with_dtype_class_errors():
2042
+ # Regression test for #25031, calling `np.dtype` with itself segfaulted.
2043
+ with pytest.raises(TypeError, match="Cannot convert np.dtype into a"):
2044
+ np.array(np.ones(10), dtype=np.dtype)
2045
+
2046
+
2047
+ @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
2048
+ class TestDTypeSignatures:
2049
+ def test_signature_dtype(self):
2050
+ sig = inspect.signature(np.dtype)
2051
+
2052
+ assert len(sig.parameters) == 4
2053
+
2054
+ assert "dtype" in sig.parameters
2055
+ assert sig.parameters["dtype"].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
2056
+ assert sig.parameters["dtype"].default is inspect.Parameter.empty
2057
+
2058
+ assert "align" in sig.parameters
2059
+ assert sig.parameters["align"].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
2060
+ assert sig.parameters["align"].default is False
2061
+
2062
+ assert "copy" in sig.parameters
2063
+ assert sig.parameters["copy"].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD
2064
+ assert sig.parameters["copy"].default is False
2065
+
2066
+ # the optional `metadata` parameter has no default, so `**kwargs` must be used
2067
+ assert "kwargs" in sig.parameters
2068
+ assert sig.parameters["kwargs"].kind is inspect.Parameter.VAR_KEYWORD
2069
+ assert sig.parameters["kwargs"].default is inspect.Parameter.empty
2070
+
2071
+ def test_signature_dtype_newbyteorder(self):
2072
+ sig = inspect.signature(np.dtype.newbyteorder)
2073
+
2074
+ assert len(sig.parameters) == 2
2075
+
2076
+ assert "self" in sig.parameters
2077
+ assert sig.parameters["self"].kind is inspect.Parameter.POSITIONAL_ONLY
2078
+ assert sig.parameters["self"].default is inspect.Parameter.empty
2079
+
2080
+ assert "new_order" in sig.parameters
2081
+ assert sig.parameters["new_order"].kind is inspect.Parameter.POSITIONAL_ONLY
2082
+ assert sig.parameters["new_order"].default == "S"
2083
+
2084
+ @pytest.mark.parametrize("typename", [
2085
+ n for n in np.dtypes.__all__ if n != "register_dlpack_dtype"
2086
+ ])
2087
+ def test_signature_dtypes_classes(self, typename: str):
2088
+ dtype_type = getattr(np.dtypes, typename)
2089
+ sig = inspect.signature(dtype_type)
2090
+
2091
+ match typename.lower().removesuffix("dtype"):
2092
+ case "bytes" | "str":
2093
+ params_expect = {"size"}
2094
+ case "void":
2095
+ params_expect = {"length"}
2096
+ case "datetime64" | "timedelta64":
2097
+ params_expect = {"unit"}
2098
+ case "string":
2099
+ # `na_object` cannot be used in the text signature because of its
2100
+ # `np._NoValue` default, which isn't supported by `inspect.signature`,
2101
+ # so `**kwargs` is used instead.
2102
+ params_expect = {"coerce", "kwargs"}
2103
+ case _:
2104
+ params_expect = set()
2105
+
2106
+ params_actual = set(sig.parameters)
2107
+ assert params_actual == params_expect