From 547c74767d00e69a1385a588b6ed00b67bf87993 Mon Sep 17 00:00:00 2001 From: Eric Wieser Date: Tue, 4 Sep 2018 23:09:13 -0700 Subject: DOC: Recommend the use of `np.ndim` over `np.isscalar`, and explain the differences --- numpy/core/numeric.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'numpy/core/numeric.py') diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 1b4818b76..2e46057ac 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1942,10 +1942,46 @@ def isscalar(num): val : bool True if `num` is a scalar type, False if it is not. + See Also + -------- + ndim : Get the number of dimensions of an array + + Notes + ----- + In almost all cases ``np.ndim(x) == 0`` should be used instead of this + function, as that will also return true for 0d arrays. This is how + numpy overloads functions in the style of the ``dx`` arguments to `gradient` + and the ``bins`` argument to `histogram`. Some key differences: + + +--------------------------------------+---------------+-------------------+ + | x |``isscalar(x)``|``np.ndim(x) == 0``| + +======================================+===============+===================+ + | PEP 3141 numeric objects (including | ``True`` | ``True`` | + | builtins) | | | + +--------------------------------------+---------------+-------------------+ + | builtin string and buffer objects | ``True`` | ``True`` | + +--------------------------------------+---------------+-------------------+ + | other builtin objects, like | ``False`` | ``True`` | + | `pathlib.Path`, `Exception`, | | | + | the result of `re.compile` | | | + +--------------------------------------+---------------+-------------------+ + | third-party objects like | ``False`` | ``True`` | + | `matplotlib.figure.Figure` | | | + +--------------------------------------+---------------+-------------------+ + | zero-dimensional numpy arrays | ``False`` | ``True`` | + +--------------------------------------+---------------+-------------------+ + | other numpy arrays | ``False`` | ``False`` | + +--------------------------------------+---------------+-------------------+ + | `list`, `tuple`, and other sequence | ``False`` | ``False`` | + | objects | | | + +--------------------------------------+---------------+-------------------+ + Examples -------- >>> np.isscalar(3.1) True + >>> np.isscalar(np.array(3.1)) + False >>> np.isscalar([3.1]) False >>> np.isscalar(False) -- cgit v1.2.1