Discussion:
How to test for type or instance of dict_values?
(too old to reply)
Thorsten Kampe
2016-11-17 12:24:54 UTC
Permalink
How can I test for type or instance of dictviews like dict_values?

`isinstance({}.values, dict_values)` gives
`NameError: name 'dict_values' is not defined`

"""
type({}.values())
<class 'dict_values'>
"""

Thorsten
Peter Otten
2016-11-17 12:38:26 UTC
Permalink
Post by Thorsten Kampe
How can I test for type or instance of dictviews like dict_values?
Why do you want to?
Post by Thorsten Kampe
`isinstance({}.values, dict_values)` gives
`NameError: name 'dict_values' is not defined`
You can "fix" this with
Post by Thorsten Kampe
dict_values = type({}.values())
isinstance({}.values(), collections.abc.ValuesView)
True
Post by Thorsten Kampe
"""
type({}.values())
<class 'dict_values'>
"""
Thorsten
Thorsten Kampe
2016-11-17 14:57:25 UTC
Permalink
* Peter Otten (Thu, 17 Nov 2016 13:38:26 +0100)
Post by Peter Otten
Post by Thorsten Kampe
How can I test for type or instance of dictviews like dict_values?
Why do you want to?
Thanks, for the `collections.abc.ValuesView` tip.

The code in question is part of an attempt to get the dimensions of
multi-dimensional lists, the `isinstance` is there in order to
exclude strings.

"""
def dim(seq):
dimension = []
while isinstance(seq, (list, tuple)):
dimension.append(len(seq))
try:
seq = seq[0]
except IndexError: # sequence is empty
break
return dimension
"""

Thorsten
Terry Reedy
2016-11-17 17:08:58 UTC
Permalink
Post by Thorsten Kampe
The code in question is part of an attempt to get the dimensions of
multi-dimensional lists, the `isinstance` is there in order to
exclude strings.
You can do the exclusion directly.
Post by Thorsten Kampe
"""
dimension = []
while not isinstance(seq, str) # or (str, bytes, ...)
Post by Thorsten Kampe
dimension.append(len(seq))
seq = seq[0]
except IndexError: # sequence is empty
break
return dimension
"""
Thorsten
--
Terry Jan Reedy
f***@gmail.com
2018-12-12 05:30:10 UTC
Permalink
Very late to the party, but I just encountered a very similar problem and found a solution:

```
import collections

obj = {"foo": "bar"}
isinstance(obj.values(), collections.abc.ValuesView) # => True
```

Hope that helps someone out there :)
Post by Terry Reedy
Post by Thorsten Kampe
The code in question is part of an attempt to get the dimensions of
multi-dimensional lists, the `isinstance` is there in order to
exclude strings.
You can do the exclusion directly.
Post by Thorsten Kampe
"""
dimension = []
while not isinstance(seq, str) # or (str, bytes, ...)
Post by Thorsten Kampe
dimension.append(len(seq))
seq = seq[0]
except IndexError: # sequence is empty
break
return dimension
"""
Thorsten
--
Terry Jan Reedy
Continue reading on narkive:
Loading...