Coverage for /usr/lib/python3/dist-packages/numpy/core/numerictypes.py: 56%

151 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2025-06-14 15:25 +0200

1""" 

2numerictypes: Define the numeric type objects 

3 

4This module is designed so "from numerictypes import \\*" is safe. 

5Exported symbols include: 

6 

7 Dictionary with all registered number types (including aliases): 

8 sctypeDict 

9 

10 Type objects (not all will be available, depends on platform): 

11 see variable sctypes for which ones you have 

12 

13 Bit-width names 

14 

15 int8 int16 int32 int64 int128 

16 uint8 uint16 uint32 uint64 uint128 

17 float16 float32 float64 float96 float128 float256 

18 complex32 complex64 complex128 complex192 complex256 complex512 

19 datetime64 timedelta64 

20 

21 c-based names 

22 

23 bool_ 

24 

25 object_ 

26 

27 void, str_, unicode_ 

28 

29 byte, ubyte, 

30 short, ushort 

31 intc, uintc, 

32 intp, uintp, 

33 int_, uint, 

34 longlong, ulonglong, 

35 

36 single, csingle, 

37 float_, complex_, 

38 longfloat, clongfloat, 

39 

40 As part of the type-hierarchy: xx -- is bit-width 

41 

42 generic 

43 +-> bool_ (kind=b) 

44 +-> number 

45 | +-> integer 

46 | | +-> signedinteger (intxx) (kind=i) 

47 | | | byte 

48 | | | short 

49 | | | intc 

50 | | | intp 

51 | | | int_ 

52 | | | longlong 

53 | | \\-> unsignedinteger (uintxx) (kind=u) 

54 | | ubyte 

55 | | ushort 

56 | | uintc 

57 | | uintp 

58 | | uint_ 

59 | | ulonglong 

60 | +-> inexact 

61 | +-> floating (floatxx) (kind=f) 

62 | | half 

63 | | single 

64 | | float_ (double) 

65 | | longfloat 

66 | \\-> complexfloating (complexxx) (kind=c) 

67 | csingle (singlecomplex) 

68 | complex_ (cfloat, cdouble) 

69 | clongfloat (longcomplex) 

70 +-> flexible 

71 | +-> character 

72 | | str_ (string_, bytes_) (kind=S) [Python 2] 

73 | | unicode_ (kind=U) [Python 2] 

74 | | 

75 | | bytes_ (string_) (kind=S) [Python 3] 

76 | | str_ (unicode_) (kind=U) [Python 3] 

77 | | 

78 | \\-> void (kind=V) 

79 \\-> object_ (not used much) (kind=O) 

80 

81""" 

82import numbers 

83import warnings 

84 

85from .multiarray import ( 

86 ndarray, array, dtype, datetime_data, datetime_as_string, 

87 busday_offset, busday_count, is_busday, busdaycalendar 

88 ) 

89from .._utils import set_module 

90 

91# we add more at the bottom 

92__all__ = ['sctypeDict', 'sctypes', 

93 'ScalarType', 'obj2sctype', 'cast', 'nbytes', 'sctype2char', 

94 'maximum_sctype', 'issctype', 'typecodes', 'find_common_type', 

95 'issubdtype', 'datetime_data', 'datetime_as_string', 

96 'busday_offset', 'busday_count', 'is_busday', 'busdaycalendar', 

97 ] 

98 

99# we don't need all these imports, but we need to keep them for compatibility 

100# for users using np.core.numerictypes.UPPER_TABLE 

101from ._string_helpers import ( 

102 english_lower, english_upper, english_capitalize, LOWER_TABLE, UPPER_TABLE 

103) 

104 

105from ._type_aliases import ( 

106 sctypeDict, 

107 allTypes, 

108 bitname, 

109 sctypes, 

110 _concrete_types, 

111 _concrete_typeinfo, 

112 _bits_of, 

113) 

114from ._dtype import _kind_name 

115 

116# we don't export these for import *, but we do want them accessible 

117# as numerictypes.bool, etc. 

118from builtins import bool, int, float, complex, object, str, bytes 

119from numpy.compat import long, unicode 

120 

121 

122# We use this later 

123generic = allTypes['generic'] 

124 

125genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16', 

126 'int32', 'uint32', 'int64', 'uint64', 'int128', 

127 'uint128', 'float16', 

128 'float32', 'float64', 'float80', 'float96', 'float128', 

129 'float256', 

130 'complex32', 'complex64', 'complex128', 'complex160', 

131 'complex192', 'complex256', 'complex512', 'object'] 

132 

133@set_module('numpy') 

134def maximum_sctype(t): 

135 """ 

136 Return the scalar type of highest precision of the same kind as the input. 

137 

138 Parameters 

139 ---------- 

140 t : dtype or dtype specifier 

141 The input data type. This can be a `dtype` object or an object that 

142 is convertible to a `dtype`. 

143 

144 Returns 

145 ------- 

146 out : dtype 

147 The highest precision data type of the same kind (`dtype.kind`) as `t`. 

148 

149 See Also 

150 -------- 

151 obj2sctype, mintypecode, sctype2char 

152 dtype 

153 

154 Examples 

155 -------- 

156 >>> np.maximum_sctype(int) 

157 <class 'numpy.int64'> 

158 >>> np.maximum_sctype(np.uint8) 

159 <class 'numpy.uint64'> 

160 >>> np.maximum_sctype(complex) 

161 <class 'numpy.complex256'> # may vary 

162 

163 >>> np.maximum_sctype(str) 

164 <class 'numpy.str_'> 

165 

166 >>> np.maximum_sctype('i2') 

167 <class 'numpy.int64'> 

168 >>> np.maximum_sctype('f4') 

169 <class 'numpy.float128'> # may vary 

170 

171 """ 

172 g = obj2sctype(t) 

173 if g is None: 

174 return t 

175 t = g 

176 base = _kind_name(dtype(t)) 

177 if base in sctypes: 

178 return sctypes[base][-1] 

179 else: 

180 return t 

181 

182 

183@set_module('numpy') 

184def issctype(rep): 

185 """ 

186 Determines whether the given object represents a scalar data-type. 

187 

188 Parameters 

189 ---------- 

190 rep : any 

191 If `rep` is an instance of a scalar dtype, True is returned. If not, 

192 False is returned. 

193 

194 Returns 

195 ------- 

196 out : bool 

197 Boolean result of check whether `rep` is a scalar dtype. 

198 

199 See Also 

200 -------- 

201 issubsctype, issubdtype, obj2sctype, sctype2char 

202 

203 Examples 

204 -------- 

205 >>> np.issctype(np.int32) 

206 True 

207 >>> np.issctype(list) 

208 False 

209 >>> np.issctype(1.1) 

210 False 

211 

212 Strings are also a scalar type: 

213 

214 >>> np.issctype(np.dtype('str')) 

215 True 

216 

217 """ 

218 if not isinstance(rep, (type, dtype)): 

219 return False 

220 try: 

221 res = obj2sctype(rep) 

222 if res and res != object_: 

223 return True 

224 return False 

225 except Exception: 

226 return False 

227 

228 

229@set_module('numpy') 

230def obj2sctype(rep, default=None): 

231 """ 

232 Return the scalar dtype or NumPy equivalent of Python type of an object. 

233 

234 Parameters 

235 ---------- 

236 rep : any 

237 The object of which the type is returned. 

238 default : any, optional 

239 If given, this is returned for objects whose types can not be 

240 determined. If not given, None is returned for those objects. 

241 

242 Returns 

243 ------- 

244 dtype : dtype or Python type 

245 The data type of `rep`. 

246 

247 See Also 

248 -------- 

249 sctype2char, issctype, issubsctype, issubdtype, maximum_sctype 

250 

251 Examples 

252 -------- 

253 >>> np.obj2sctype(np.int32) 

254 <class 'numpy.int32'> 

255 >>> np.obj2sctype(np.array([1., 2.])) 

256 <class 'numpy.float64'> 

257 >>> np.obj2sctype(np.array([1.j])) 

258 <class 'numpy.complex128'> 

259 

260 >>> np.obj2sctype(dict) 

261 <class 'numpy.object_'> 

262 >>> np.obj2sctype('string') 

263 

264 >>> np.obj2sctype(1, default=list) 

265 <class 'list'> 

266 

267 """ 

268 # prevent abstract classes being upcast 

269 if isinstance(rep, type) and issubclass(rep, generic): 

270 return rep 

271 # extract dtype from arrays 

272 if isinstance(rep, ndarray): 

273 return rep.dtype.type 

274 # fall back on dtype to convert 

275 try: 

276 res = dtype(rep) 

277 except Exception: 

278 return default 

279 else: 

280 return res.type 

281 

282 

283@set_module('numpy') 

284def issubclass_(arg1, arg2): 

285 """ 

286 Determine if a class is a subclass of a second class. 

287 

288 `issubclass_` is equivalent to the Python built-in ``issubclass``, 

289 except that it returns False instead of raising a TypeError if one 

290 of the arguments is not a class. 

291 

292 Parameters 

293 ---------- 

294 arg1 : class 

295 Input class. True is returned if `arg1` is a subclass of `arg2`. 

296 arg2 : class or tuple of classes. 

297 Input class. If a tuple of classes, True is returned if `arg1` is a 

298 subclass of any of the tuple elements. 

299 

300 Returns 

301 ------- 

302 out : bool 

303 Whether `arg1` is a subclass of `arg2` or not. 

304 

305 See Also 

306 -------- 

307 issubsctype, issubdtype, issctype 

308 

309 Examples 

310 -------- 

311 >>> np.issubclass_(np.int32, int) 

312 False 

313 >>> np.issubclass_(np.int32, float) 

314 False 

315 >>> np.issubclass_(np.float64, float) 

316 True 

317 

318 """ 

319 try: 

320 return issubclass(arg1, arg2) 

321 except TypeError: 

322 return False 

323 

324 

325@set_module('numpy') 

326def issubsctype(arg1, arg2): 

327 """ 

328 Determine if the first argument is a subclass of the second argument. 

329 

330 Parameters 

331 ---------- 

332 arg1, arg2 : dtype or dtype specifier 

333 Data-types. 

334 

335 Returns 

336 ------- 

337 out : bool 

338 The result. 

339 

340 See Also 

341 -------- 

342 issctype, issubdtype, obj2sctype 

343 

344 Examples 

345 -------- 

346 >>> np.issubsctype('S8', str) 

347 False 

348 >>> np.issubsctype(np.array([1]), int) 

349 True 

350 >>> np.issubsctype(np.array([1]), float) 

351 False 

352 

353 """ 

354 return issubclass(obj2sctype(arg1), obj2sctype(arg2)) 

355 

356 

357@set_module('numpy') 

358def issubdtype(arg1, arg2): 

359 r""" 

360 Returns True if first argument is a typecode lower/equal in type hierarchy. 

361 

362 This is like the builtin :func:`issubclass`, but for `dtype`\ s. 

363 

364 Parameters 

365 ---------- 

366 arg1, arg2 : dtype_like 

367 `dtype` or object coercible to one 

368 

369 Returns 

370 ------- 

371 out : bool 

372 

373 See Also 

374 -------- 

375 :ref:`arrays.scalars` : Overview of the numpy type hierarchy. 

376 issubsctype, issubclass_ 

377 

378 Examples 

379 -------- 

380 `issubdtype` can be used to check the type of arrays: 

381 

382 >>> ints = np.array([1, 2, 3], dtype=np.int32) 

383 >>> np.issubdtype(ints.dtype, np.integer) 

384 True 

385 >>> np.issubdtype(ints.dtype, np.floating) 

386 False 

387 

388 >>> floats = np.array([1, 2, 3], dtype=np.float32) 

389 >>> np.issubdtype(floats.dtype, np.integer) 

390 False 

391 >>> np.issubdtype(floats.dtype, np.floating) 

392 True 

393 

394 Similar types of different sizes are not subdtypes of each other: 

395 

396 >>> np.issubdtype(np.float64, np.float32) 

397 False 

398 >>> np.issubdtype(np.float32, np.float64) 

399 False 

400 

401 but both are subtypes of `floating`: 

402 

403 >>> np.issubdtype(np.float64, np.floating) 

404 True 

405 >>> np.issubdtype(np.float32, np.floating) 

406 True 

407 

408 For convenience, dtype-like objects are allowed too: 

409 

410 >>> np.issubdtype('S1', np.string_) 

411 True 

412 >>> np.issubdtype('i4', np.signedinteger) 

413 True 

414 

415 """ 

416 if not issubclass_(arg1, generic): 

417 arg1 = dtype(arg1).type 

418 if not issubclass_(arg2, generic): 

419 arg2 = dtype(arg2).type 

420 

421 return issubclass(arg1, arg2) 

422 

423 

424# This dictionary allows look up based on any alias for an array data-type 

425class _typedict(dict): 

426 """ 

427 Base object for a dictionary for look-up with any alias for an array dtype. 

428 

429 Instances of `_typedict` can not be used as dictionaries directly, 

430 first they have to be populated. 

431 

432 """ 

433 

434 def __getitem__(self, obj): 

435 return dict.__getitem__(self, obj2sctype(obj)) 

436 

437nbytes = _typedict() 

438_alignment = _typedict() 

439_maxvals = _typedict() 

440_minvals = _typedict() 

441def _construct_lookups(): 

442 for name, info in _concrete_typeinfo.items(): 

443 obj = info.type 

444 nbytes[obj] = info.bits // 8 

445 _alignment[obj] = info.alignment 

446 if len(info) > 5: 

447 _maxvals[obj] = info.max 

448 _minvals[obj] = info.min 

449 else: 

450 _maxvals[obj] = None 

451 _minvals[obj] = None 

452 

453_construct_lookups() 

454 

455 

456@set_module('numpy') 

457def sctype2char(sctype): 

458 """ 

459 Return the string representation of a scalar dtype. 

460 

461 Parameters 

462 ---------- 

463 sctype : scalar dtype or object 

464 If a scalar dtype, the corresponding string character is 

465 returned. If an object, `sctype2char` tries to infer its scalar type 

466 and then return the corresponding string character. 

467 

468 Returns 

469 ------- 

470 typechar : str 

471 The string character corresponding to the scalar type. 

472 

473 Raises 

474 ------ 

475 ValueError 

476 If `sctype` is an object for which the type can not be inferred. 

477 

478 See Also 

479 -------- 

480 obj2sctype, issctype, issubsctype, mintypecode 

481 

482 Examples 

483 -------- 

484 >>> for sctype in [np.int32, np.double, np.complex_, np.string_, np.ndarray]: 

485 ... print(np.sctype2char(sctype)) 

486 l # may vary 

487 d 

488 D 

489 S 

490 O 

491 

492 >>> x = np.array([1., 2-1.j]) 

493 >>> np.sctype2char(x) 

494 'D' 

495 >>> np.sctype2char(list) 

496 'O' 

497 

498 """ 

499 sctype = obj2sctype(sctype) 

500 if sctype is None: 

501 raise ValueError("unrecognized type") 

502 if sctype not in _concrete_types: 

503 # for compatibility 

504 raise KeyError(sctype) 

505 return dtype(sctype).char 

506 

507# Create dictionary of casting functions that wrap sequences 

508# indexed by type or type character 

509cast = _typedict() 

510for key in _concrete_types: 

511 cast[key] = lambda x, k=key: array(x, copy=False).astype(k) 

512 

513 

514def _scalar_type_key(typ): 

515 """A ``key`` function for `sorted`.""" 

516 dt = dtype(typ) 

517 return (dt.kind.lower(), dt.itemsize) 

518 

519 

520ScalarType = [int, float, complex, bool, bytes, str, memoryview] 

521ScalarType += sorted(_concrete_types, key=_scalar_type_key) 

522ScalarType = tuple(ScalarType) 

523 

524 

525# Now add the types we've determined to this module 

526for key in allTypes: 

527 globals()[key] = allTypes[key] 

528 __all__.append(key) 

529 

530del key 

531 

532typecodes = {'Character':'c', 

533 'Integer':'bhilqp', 

534 'UnsignedInteger':'BHILQP', 

535 'Float':'efdg', 

536 'Complex':'FDG', 

537 'AllInteger':'bBhHiIlLqQpP', 

538 'AllFloat':'efdgFDG', 

539 'Datetime': 'Mm', 

540 'All':'?bhilqpBHILQPefdgFDGSUVOMm'} 

541 

542# backwards compatibility --- deprecated name 

543# Formal deprecation: Numpy 1.20.0, 2020-10-19 (see numpy/__init__.py) 

544typeDict = sctypeDict 

545 

546# b -> boolean 

547# u -> unsigned integer 

548# i -> signed integer 

549# f -> floating point 

550# c -> complex 

551# M -> datetime 

552# m -> timedelta 

553# S -> string 

554# U -> Unicode string 

555# V -> record 

556# O -> Python object 

557_kind_list = ['b', 'u', 'i', 'f', 'c', 'S', 'U', 'V', 'O', 'M', 'm'] 

558 

559__test_types = '?'+typecodes['AllInteger'][:-2]+typecodes['AllFloat']+'O' 

560__len_test_types = len(__test_types) 

561 

562# Keep incrementing until a common type both can be coerced to 

563# is found. Otherwise, return None 

564def _find_common_coerce(a, b): 

565 if a > b: 

566 return a 

567 try: 

568 thisind = __test_types.index(a.char) 

569 except ValueError: 

570 return None 

571 return _can_coerce_all([a, b], start=thisind) 

572 

573# Find a data-type that all data-types in a list can be coerced to 

574def _can_coerce_all(dtypelist, start=0): 

575 N = len(dtypelist) 

576 if N == 0: 

577 return None 

578 if N == 1: 

579 return dtypelist[0] 

580 thisind = start 

581 while thisind < __len_test_types: 

582 newdtype = dtype(__test_types[thisind]) 

583 numcoerce = len([x for x in dtypelist if newdtype >= x]) 

584 if numcoerce == N: 

585 return newdtype 

586 thisind += 1 

587 return None 

588 

589def _register_types(): 

590 numbers.Integral.register(integer) 

591 numbers.Complex.register(inexact) 

592 numbers.Real.register(floating) 

593 numbers.Number.register(number) 

594 

595_register_types() 

596 

597 

598@set_module('numpy') 

599def find_common_type(array_types, scalar_types): 

600 """ 

601 Determine common type following standard coercion rules. 

602 

603 .. deprecated:: NumPy 1.25 

604 

605 This function is deprecated, use `numpy.promote_types` or 

606 `numpy.result_type` instead. To achieve semantics for the 

607 `scalar_types` argument, use `numpy.result_type` and pass the Python 

608 values `0`, `0.0`, or `0j`. 

609 This will give the same results in almost all cases. 

610 More information and rare exception can be found in the 

611 `NumPy 1.25 release notes <https://numpy.org/devdocs/release/1.25.0-notes.html>`_. 

612 

613 Parameters 

614 ---------- 

615 array_types : sequence 

616 A list of dtypes or dtype convertible objects representing arrays. 

617 scalar_types : sequence 

618 A list of dtypes or dtype convertible objects representing scalars. 

619 

620 Returns 

621 ------- 

622 datatype : dtype 

623 The common data type, which is the maximum of `array_types` ignoring 

624 `scalar_types`, unless the maximum of `scalar_types` is of a 

625 different kind (`dtype.kind`). If the kind is not understood, then 

626 None is returned. 

627 

628 See Also 

629 -------- 

630 dtype, common_type, can_cast, mintypecode 

631 

632 Examples 

633 -------- 

634 >>> np.find_common_type([], [np.int64, np.float32, complex]) 

635 dtype('complex128') 

636 >>> np.find_common_type([np.int64, np.float32], []) 

637 dtype('float64') 

638 

639 The standard casting rules ensure that a scalar cannot up-cast an 

640 array unless the scalar is of a fundamentally different kind of data 

641 (i.e. under a different hierarchy in the data type hierarchy) then 

642 the array: 

643 

644 >>> np.find_common_type([np.float32], [np.int64, np.float64]) 

645 dtype('float32') 

646 

647 Complex is of a different type, so it up-casts the float in the 

648 `array_types` argument: 

649 

650 >>> np.find_common_type([np.float32], [complex]) 

651 dtype('complex128') 

652 

653 Type specifier strings are convertible to dtypes and can therefore 

654 be used instead of dtypes: 

655 

656 >>> np.find_common_type(['f4', 'f4', 'i4'], ['c8']) 

657 dtype('complex128') 

658 

659 """ 

660 # Deprecated 2022-11-07, NumPy 1.25 

661 warnings.warn( 

662 "np.find_common_type is deprecated. Please use `np.result_type` " 

663 "or `np.promote_types`.\n" 

664 "See https://numpy.org/devdocs/release/1.25.0-notes.html and the " 

665 "docs for more information. (Deprecated NumPy 1.25)", 

666 DeprecationWarning, stacklevel=2) 

667 

668 array_types = [dtype(x) for x in array_types] 

669 scalar_types = [dtype(x) for x in scalar_types] 

670 

671 maxa = _can_coerce_all(array_types) 

672 maxsc = _can_coerce_all(scalar_types) 

673 

674 if maxa is None: 

675 return maxsc 

676 

677 if maxsc is None: 

678 return maxa 

679 

680 try: 

681 index_a = _kind_list.index(maxa.kind) 

682 index_sc = _kind_list.index(maxsc.kind) 

683 except ValueError: 

684 return None 

685 

686 if index_sc > index_a: 

687 return _find_common_coerce(maxsc, maxa) 

688 else: 

689 return maxa