8000 DOC: Recommend the use of `np.ndim` over `np.isscalar`, and explain t… · numpy/numpy@547c747 · GitHub
[go: up one dir, main page]

Skip to content

Commit 547c747

Browse files
committed
DOC: Recommend the use of np.ndim over np.isscalar, and explain the differences
1 parent 058851c commit 547c747

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

numpy/core/numeric.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1942,10 +1942,46 @@ def isscalar(num):
19421942
val : bool
19431943
True if `num` is a scalar type, False if it is not.
19441944
1945+
See Also
1946+
--------
1947+
ndim : Get the number of dimensions of an array
1948+
1949+
Notes
1950+
-----
1951+
In almost all cases ``np.ndim(x) == 0`` should be used instead of this
1952+
function, as that will also return true for 0d arrays. This is how
1953+
numpy overloads functions in the style of the ``dx`` arguments to `gradient`
1954+
and the ``bins`` argument to `histogram`. Some key differences:
1955+
1956+
+--------------------------------------+---------------+-------------------+
1957+
| x |``isscalar(x)``|``np.ndim(x) == 0``|
1958+
+======================================+===============+===================+
1959+
| PEP 3141 numeric objects (including | ``True`` | ``True`` |
1960+
| builtins) | | |
1961+
+--------------------------------------+---------------+-------------------+
1962+
| builtin string and buffer objects | ``True`` | ``True`` |
1963+
+--------------------------------------+---------------+-------------------+
1964+
| other builtin objects, like | ``False`` | ``True`` |
1965+
| `pathlib.Path`, `Exception`, | | |
1966+
| the result of `re.compile` | | |
1967+
+--------------------------------------+---------------+-------------------+
1968+
| third-party objects like | ``False`` | ``True`` |
1969+
| `matplotlib.figure.Figure` | | |
1970+
+--------------------------------------+---------------+-------------------+
1971+
| zero-dimensional numpy arrays | ``False`` | ``True`` |
1972+
+--------------------------------------+---------------+-------------------+
1973+
| other numpy arrays | ``False`` | ``False`` |
1974+
+--------------------------------------+---------------+-------------------+
1975+
| `list`, `tuple`, and other sequence | ``False`` | ``False`` |
1976+
| objects | | |
1977+
+--------------------------------------+---------------+-------------------+
1978+
19451979
Examples
19461980
--------
19471981
>>> np.isscalar(3.1)
19481982
True
1983+
>>> np.isscalar(np.array(3.1))
1984+
False
19491985
>>> np.isscalar([3.1])
19501986
False
19511987
>>> np.isscalar(False)

0 commit comments

Comments
 (0)
0