Coverage for /usr/lib/python3/dist-packages/numpy/core/numerictypes.py: 56%
151 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
1"""
2numerictypes: Define the numeric type objects
4This module is designed so "from numerictypes import \\*" is safe.
5Exported symbols include:
7 Dictionary with all registered number types (including aliases):
8 sctypeDict
10 Type objects (not all will be available, depends on platform):
11 see variable sctypes for which ones you have
13 Bit-width names
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
21 c-based names
23 bool_
25 object_
27 void, str_, unicode_
29 byte, ubyte,
30 short, ushort
31 intc, uintc,
32 intp, uintp,
33 int_, uint,
34 longlong, ulonglong,
36 single, csingle,
37 float_, complex_,
38 longfloat, clongfloat,
40 As part of the type-hierarchy: xx -- is bit-width
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)
81"""
82import numbers
83import warnings
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
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 ]
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)
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
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
122# We use this later
123generic = allTypes['generic']
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']
133@set_module('numpy')
134def maximum_sctype(t):
135 """
136 Return the scalar type of highest precision of the same kind as the input.
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`.
144 Returns
145 -------
146 out : dtype
147 The highest precision data type of the same kind (`dtype.kind`) as `t`.
149 See Also
150 --------
151 obj2sctype, mintypecode, sctype2char
152 dtype
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
163 >>> np.maximum_sctype(str)
164 <class 'numpy.str_'>
166 >>> np.maximum_sctype('i2')
167 <class 'numpy.int64'>
168 >>> np.maximum_sctype('f4')
169 <class 'numpy.float128'> # may vary
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
183@set_module('numpy')
184def issctype(rep):
185 """
186 Determines whether the given object represents a scalar data-type.
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.
194 Returns
195 -------
196 out : bool
197 Boolean result of check whether `rep` is a scalar dtype.
199 See Also
200 --------
201 issubsctype, issubdtype, obj2sctype, sctype2char
203 Examples
204 --------
205 >>> np.issctype(np.int32)
206 True
207 >>> np.issctype(list)
208 False
209 >>> np.issctype(1.1)
210 False
212 Strings are also a scalar type:
214 >>> np.issctype(np.dtype('str'))
215 True
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
229@set_module('numpy')
230def obj2sctype(rep, default=None):
231 """
232 Return the scalar dtype or NumPy equivalent of Python type of an object.
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.
242 Returns
243 -------
244 dtype : dtype or Python type
245 The data type of `rep`.
247 See Also
248 --------
249 sctype2char, issctype, issubsctype, issubdtype, maximum_sctype
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'>
260 >>> np.obj2sctype(dict)
261 <class 'numpy.object_'>
262 >>> np.obj2sctype('string')
264 >>> np.obj2sctype(1, default=list)
265 <class 'list'>
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
283@set_module('numpy')
284def issubclass_(arg1, arg2):
285 """
286 Determine if a class is a subclass of a second class.
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.
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.
300 Returns
301 -------
302 out : bool
303 Whether `arg1` is a subclass of `arg2` or not.
305 See Also
306 --------
307 issubsctype, issubdtype, issctype
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
318 """
319 try:
320 return issubclass(arg1, arg2)
321 except TypeError:
322 return False
325@set_module('numpy')
326def issubsctype(arg1, arg2):
327 """
328 Determine if the first argument is a subclass of the second argument.
330 Parameters
331 ----------
332 arg1, arg2 : dtype or dtype specifier
333 Data-types.
335 Returns
336 -------
337 out : bool
338 The result.
340 See Also
341 --------
342 issctype, issubdtype, obj2sctype
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
353 """
354 return issubclass(obj2sctype(arg1), obj2sctype(arg2))
357@set_module('numpy')
358def issubdtype(arg1, arg2):
359 r"""
360 Returns True if first argument is a typecode lower/equal in type hierarchy.
362 This is like the builtin :func:`issubclass`, but for `dtype`\ s.
364 Parameters
365 ----------
366 arg1, arg2 : dtype_like
367 `dtype` or object coercible to one
369 Returns
370 -------
371 out : bool
373 See Also
374 --------
375 :ref:`arrays.scalars` : Overview of the numpy type hierarchy.
376 issubsctype, issubclass_
378 Examples
379 --------
380 `issubdtype` can be used to check the type of arrays:
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
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
394 Similar types of different sizes are not subdtypes of each other:
396 >>> np.issubdtype(np.float64, np.float32)
397 False
398 >>> np.issubdtype(np.float32, np.float64)
399 False
401 but both are subtypes of `floating`:
403 >>> np.issubdtype(np.float64, np.floating)
404 True
405 >>> np.issubdtype(np.float32, np.floating)
406 True
408 For convenience, dtype-like objects are allowed too:
410 >>> np.issubdtype('S1', np.string_)
411 True
412 >>> np.issubdtype('i4', np.signedinteger)
413 True
415 """
416 if not issubclass_(arg1, generic):
417 arg1 = dtype(arg1).type
418 if not issubclass_(arg2, generic):
419 arg2 = dtype(arg2).type
421 return issubclass(arg1, arg2)
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.
429 Instances of `_typedict` can not be used as dictionaries directly,
430 first they have to be populated.
432 """
434 def __getitem__(self, obj):
435 return dict.__getitem__(self, obj2sctype(obj))
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
453_construct_lookups()
456@set_module('numpy')
457def sctype2char(sctype):
458 """
459 Return the string representation of a scalar dtype.
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.
468 Returns
469 -------
470 typechar : str
471 The string character corresponding to the scalar type.
473 Raises
474 ------
475 ValueError
476 If `sctype` is an object for which the type can not be inferred.
478 See Also
479 --------
480 obj2sctype, issctype, issubsctype, mintypecode
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
492 >>> x = np.array([1., 2-1.j])
493 >>> np.sctype2char(x)
494 'D'
495 >>> np.sctype2char(list)
496 'O'
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
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)
514def _scalar_type_key(typ):
515 """A ``key`` function for `sorted`."""
516 dt = dtype(typ)
517 return (dt.kind.lower(), dt.itemsize)
520ScalarType = [int, float, complex, bool, bytes, str, memoryview]
521ScalarType += sorted(_concrete_types, key=_scalar_type_key)
522ScalarType = tuple(ScalarType)
525# Now add the types we've determined to this module
526for key in allTypes:
527 globals()[key] = allTypes[key]
528 __all__.append(key)
530del key
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'}
542# backwards compatibility --- deprecated name
543# Formal deprecation: Numpy 1.20.0, 2020-10-19 (see numpy/__init__.py)
544typeDict = sctypeDict
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']
559__test_types = '?'+typecodes['AllInteger'][:-2]+typecodes['AllFloat']+'O'
560__len_test_types = len(__test_types)
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)
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
589def _register_types():
590 numbers.Integral.register(integer)
591 numbers.Complex.register(inexact)
592 numbers.Real.register(floating)
593 numbers.Number.register(number)
595_register_types()
598@set_module('numpy')
599def find_common_type(array_types, scalar_types):
600 """
601 Determine common type following standard coercion rules.
603 .. deprecated:: NumPy 1.25
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>`_.
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.
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.
628 See Also
629 --------
630 dtype, common_type, can_cast, mintypecode
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')
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:
644 >>> np.find_common_type([np.float32], [np.int64, np.float64])
645 dtype('float32')
647 Complex is of a different type, so it up-casts the float in the
648 `array_types` argument:
650 >>> np.find_common_type([np.float32], [complex])
651 dtype('complex128')
653 Type specifier strings are convertible to dtypes and can therefore
654 be used instead of dtypes:
656 >>> np.find_common_type(['f4', 'f4', 'i4'], ['c8'])
657 dtype('complex128')
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)
668 array_types = [dtype(x) for x in array_types]
669 scalar_types = [dtype(x) for x in scalar_types]
671 maxa = _can_coerce_all(array_types)
672 maxsc = _can_coerce_all(scalar_types)
674 if maxa is None:
675 return maxsc
677 if maxsc is None:
678 return maxa
680 try:
681 index_a = _kind_list.index(maxa.kind)
682 index_sc = _kind_list.index(maxsc.kind)
683 except ValueError:
684 return None
686 if index_sc > index_a:
687 return _find_common_coerce(maxsc, maxa)
688 else:
689 return maxa