Repository: spyder-ide/spyder

Issue:
Creating a pint Quantity in the console fails
## Description

### What steps will reproduce the problem?

<!--- You can use Markdown here --->

run:
```
import pint
a = pint.Quantity(12, 's')
```

### Traceback
```python-traceback
Exception in comms call get_namespace_view:
  File "c:\users\quentin.peter\spyder-kernels\spyder_kernels\comms\commbase.py", line 343, in _handle_remote_call
    buffer['call_kwargs'])
  File "c:\users\quentin.peter\spyder-kernels\spyder_kernels\comms\commbase.py", line 354, in _remote_callback
    *call_args, **call_kwargs)
  File "c:\users\quentin.peter\spyder-kernels\spyder_kernels\console\kernel.py", line 135, in get_namespace_view
    view = make_remote_view(ns, settings, EXCLUDED_NAMES)
  File "c:\users\quentin.peter\spyder-kernels\spyder_kernels\utils\nsview.py", line 715, in make_remote_view
    'size':  get_size(value),
  File "c:\users\quentin.peter\spyder-kernels\spyder_kernels\utils\nsview.py", line 138, in get_size
    return len(item)
  File "C:\Users\Quentin.Peter\AppData\Local\Continuum\anaconda3\lib\site-packages\pint\quantity.py", line 1684, in __len__
    return len(self._magnitude)
TypeError: object of type 'int' has no len()
```

## Versions

* Spyder version: 4.2.0.dev0 7945c774e
* Python version: 3.7.6
* Qt version: 5.12.8
* PyQt5 version: 5.12.3
* Operating System: Windows 10

### Dependencies

```

# Mandatory:
atomicwrites >=1.2.0           :  1.4.0 (OK)
chardet >=2.0.0                :  3.0.4 (OK)
cloudpickle >=0.5.0            :  1.3.0 (OK)
diff_match_patch >=20181111    :  20181111 (OK)
intervaltree                   :  None (OK)
IPython >=4.0                  :  7.18.1 (OK)
jedi =0.17.2                   :  0.17.2 (OK)
nbconvert >=4.0                :  6.0.6 (OK)
numpydoc >=0.6.0               :  0.9.2 (OK)
paramiko >=2.4.0               :  2.7.1 (OK)
parso =0.7.0                   :  0.7.0 (OK)
pexpect >=4.4.0                :  4.8.0 (OK)
pickleshare >=0.4              :  0.7.5 (OK)
psutil >=5.3                   :  5.7.2 (OK)
pygments >=2.0                 :  2.7.1 (OK)
pylint >=1.0                   :  2.5.2 (OK)
pyls >=0.35.0;<1.0.0           :  0.35.1 (OK)
qdarkstyle >=2.8               :  2.8.1 (OK)
qtawesome >=0.5.7              :  0.7.0 (OK)
qtconsole >=4.7.7              :  4.7.7 (OK)
qtpy >=1.5.0                   :  1.9.0 (OK)
rtree >=0.8.3                  :  0.9.4 (OK)
sphinx >=0.6.6                 :  3.0.4 (OK)
spyder_kernels >=1.9.4;<1.10.0 :  1.10.0.dev0 (OK)
watchdog                       :  None (OK)
zmq >=17                       :  19.0.2 (OK)

# Optional:
cython >=0.21                  :  0.29.21 (OK)
matplotlib >=2.0.0             :  3.2.2 (OK)
numpy >=1.7                    :  1.19.1 (OK)
pandas >=1.1.1                 :  1.0.5 (NOK)
scipy >=0.17.0                 :  1.5.0 (OK)
sympy >=0.7.3                  :  1.6.1 (OK)
```



Discussion:

Resolving patch:
diff --git a/external-deps/spyder-kernels/setup.py b/external-deps/spyder-kernels/setup.py
--- a/external-deps/spyder-kernels/setup.py
+++ b/external-deps/spyder-kernels/setup.py
@@ -57,6 +57,7 @@ def get_version(module='spyder_kernels'):
     'pytest-cov',
     'scipy',
     'xarray',
+    'pillow',
 ]
 
 setup(
diff --git a/external-deps/spyder-kernels/spyder_kernels/utils/nsview.py b/external-deps/spyder-kernels/spyder_kernels/utils/nsview.py
--- a/external-deps/spyder-kernels/spyder_kernels/utils/nsview.py
+++ b/external-deps/spyder-kernels/spyder_kernels/utils/nsview.py
@@ -36,7 +36,7 @@ class FakeObject(object):
 # Numpy arrays and numeric types support
 #==============================================================================
 try:
-    from numpy import (ndarray, array, matrix, recarray,
+    from numpy import (ndarray, array, matrix, recarray, integer,
                        int64, int32, int16, int8, uint64, uint32, uint16, uint8,
                        float64, float32, float16, complex64, complex128, bool_)
     from numpy.ma import MaskedArray
@@ -118,24 +118,33 @@ def try_to_eval(value):
     except (NameError, SyntaxError, ImportError):
         return value
 
-    
+
 def get_size(item):
-    """Return size of an item of arbitrary type"""
-    if isinstance(item, (list, set, tuple, dict)):
-        return len(item)
-    elif isinstance(item, (ndarray, MaskedArray)):
-        return item.shape
-    elif isinstance(item, Image):
-        return item.size
-    if isinstance(item, (DataFrame, Index, Series)):
-        try:
-            return item.shape
-        except RecursionError:
-            # This is necessary to avoid an error when trying to
-            # get the shape of these objects.
-            # Fixes spyder-ide/spyder-kernels#217
-            return (-1, -1)
-    else:
+    """Return shape/size/len of an item of arbitrary type"""
+    try:
+        if hasattr(item, 'shape') and isinstance(item.shape, (tuple, integer)):
+            try:
+                if item.shape:
+                    return item.shape
+                else:
+                    # Scalar value
+                    return 1
+            except RecursionError:
+                # This is necessary to avoid an error when trying to
+                # get the shape of these objects.
+                # Fixes spyder-ide/spyder-kernels#217
+                return (-1, -1)
+        elif hasattr(item, 'size') and isinstance(item.size, (tuple, integer)):
+            try:
+                return item.size
+            except RecursionError:
+                return (-1, -1)
+        elif hasattr(item, '__len__'):
+            return len(item)
+        else:
+            return 1
+    except Exception:
+        # There is one item
         return 1
 
 
@@ -714,4 +723,4 @@ def make_remote_view(data, settings, more_excluded_names=None):
                        'size':  get_size(value),
                        'color': get_color_name(value),
                        'view':  view}
-    return remote
+    return remote
\ No newline at end of file


Test patch:
diff --git a/external-deps/spyder-kernels/requirements/tests.txt b/external-deps/spyder-kernels/requirements/tests.txt
--- a/external-deps/spyder-kernels/requirements/tests.txt
+++ b/external-deps/spyder-kernels/requirements/tests.txt
@@ -10,3 +10,4 @@ pytest
 pytest-cov
 scipy
 xarray
+pillow
\ No newline at end of file
diff --git a/external-deps/spyder-kernels/spyder_kernels/utils/tests/test_nsview.py b/external-deps/spyder-kernels/spyder_kernels/utils/tests/test_nsview.py
--- a/external-deps/spyder-kernels/spyder_kernels/utils/tests/test_nsview.py
+++ b/external-deps/spyder-kernels/spyder_kernels/utils/tests/test_nsview.py
@@ -18,12 +18,13 @@
 import pandas as pd
 import pytest
 import xarray as xr
+import PIL
 
 # Local imports
 from spyder_kernels.py3compat import PY2
 from spyder_kernels.utils.nsview import (sort_against, is_supported,
-                                         value_to_display,
-                                         get_supported_types)
+                                         value_to_display, get_size,
+                                         get_supported_types, Image)
 
 def generate_complex_object():
     """Taken from issue #4221."""
@@ -41,6 +42,41 @@ def generate_complex_object():
 
 # --- Tests
 # -----------------------------------------------------------------------------
+def test_get_size():
+    """Test that the size of all values is returned correctly"""
+
+    class RecursionClassNoLen():
+        def __getattr__(self, name):
+            if name=='size': return self.name
+            else:
+                return super(object, self).__getattribute__(name)
+
+
+    length = [list([1,2,3]), tuple([1,2,3]), set([1,2,3]), '123',
+              {1:1, 2:2, 3:3}]
+    for obj in length:
+        assert get_size(obj) == 3
+
+    df = pd.DataFrame([[1,2,3], [1,2,3]])
+    assert get_size(df) == (2, 3)
+
+    df = pd.Series([1,2,3])
+    assert get_size(df) == (3,)
+
+    df = pd.Index([1,2,3])
+    assert get_size(df) == (3,)
+
+    arr = np.array([[1,2,3], [1,2,3]], dtype=np.complex)
+    assert get_size(arr) == (2, 3)
+
+    img = PIL.Image.new('RGB', (256,256))
+    assert get_size(img) == (256,256)
+
+    obj = RecursionClassNoLen()
+    assert get_size(obj) == 1
+
+
+
 def test_sort_against():
     lista = [5, 6, 7]
     listb = [2, 3, 1]
@@ -264,4 +300,4 @@ def test_ellipses(tmpdir):
 
 
 if __name__ == "__main__":
-    pytest.main()
+    pytest.main()
\ No newline at end of file
diff --git a/spyder/plugins/variableexplorer/widgets/tests/test_collectioneditor.py b/spyder/plugins/variableexplorer/widgets/tests/test_collectioneditor.py
--- a/spyder/plugins/variableexplorer/widgets/tests/test_collectioneditor.py
+++ b/spyder/plugins/variableexplorer/widgets/tests/test_collectioneditor.py
@@ -866,7 +866,7 @@ def test_dicts_natural_sorting(qtbot):
         'GUI sorting fail'
 
 
-def test_dicts_natural_sorting_mixed_types(qtbot):
+def test_dicts_natural_sorting_mixed_types():
     """
     Test that natural sorting actually does what it should do.
     testing for issue 13733, as mixed types were sorted incorrectly.
@@ -890,27 +890,27 @@ def test_dicts_natural_sorting_mixed_types(qtbot):
 
     assert keys == ['aStr', 'DSeries', 'kDict']
     assert types == ['str', 'Series', 'dict']
-    assert sizes == [1, (0,), 2]
+    assert sizes == [str_size, (0,), 2]
 
     assert data_table(cm, 3, 3) == [['aStr', 'DSeries', 'kDict'],
                                     ['str', 'Series', 'dict'],
-                                    [1, '(0,)', 2]]
+                                    [str_size, '(0,)', 2]]
 
     # insert an item and check that it is still sorted correctly
     editor.widget.editor.new_value('List', [1, 2, 3])
     assert data_table(cm, 4, 3) == [['aStr', 'DSeries', 'kDict', 'List'],
                                     ['str', 'Series', 'dict', 'list'],
-                                    [1, '(0,)', 2, 3]]
+                                    [str_size, '(0,)', 2, 3]]
     cm.sort(0)
     assert data_table(cm, 4, 3) == [['aStr', 'DSeries', 'kDict', 'List'],
                                     ['str', 'Series', 'dict', 'list'],
-                                    [1, '(0,)', 2, 3]]
+                                    [str_size, '(0,)', 2, 3]]
 
     # now sort for types
     cm.sort(1)
     assert data_table(cm, 4, 3) == [['DSeries', 'kDict', 'List', 'aStr'],
                                     ['Series', 'dict', 'list', 'str'],
-                                    ['(0,)', 2, 3, 1]]
+                                    ['(0,)', 2, 3, str_size]]
 
     # now sort for sizes
     cm.sort(2)