8000 DOC: Document how to check for a specific dtype by timhoffm · Pull Request #25300 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

DOC: Document how to check for a specific dtype #25300

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions doc/source/reference/arrays.dtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,50 @@ Type strings
>>> dt = np.dtype(('i4', [('r','u1'),('g','u1'),('b','u1'),('a','u1')]))


Checking the data type
======================
When checking for a specific data type, use ``==`` comparison.

.. admonition:: Example

>>> a = np.array([1, 2], dtype=np.float32)
>>> a.dtype == np.float32
True

As opposed to python types, a comparison using ``is`` should not be used.

First, NumPy treats data type specifications (everything that can be passed to
the :class:`dtype` constructor) as equivalent to the data type object itself.
This equivalence can only be handled through ``==``, not through ``is``.

.. admonition:: Example

A :class:`dtype` object is equal to all data type specifications that are
equivalent to it.

>>> a = np.array([1, 2], dtype=float)
>>> a.dtype == np.dtype(np.float64)
True
>>> a.dtype == np.float64
True
>>> a.dtype == float
True
>>> a.dtype == "float64"
True
>>> a.dtype == "d"
True

Second, there is no guarantee that data type objects are singletons.

.. admonition:: Example

Do not use ``is`` because data type objects may or may not be singletons.

>>> np.dtype(float) is np.dtype(float)
True
>>> np.dtype([('a', float)]) is np.dtype([('a', float)])
False

:class:`dtype`
==============

Expand Down
0