Checking the instance of multiple items at once
Suppose you have a list of items, which are all instances of some class
For example:
>>>result
[<DjangoProject.itemModel.SomeProperty bobject at 0xaeb0bcc>, <DjangoProject.itemModel.SomeProperty at 0xae8a6ac>, <DjangoProject.itemModel.SomeProperty object at 0xaf4a50c>]
Checking if these items can be done with isinstace, how ever doing the
following, will yield an unwanted result:
>>>isinstace(result, DjangoProject.itemModel.SomeProperty)
This is since result is a list. OK so we can do:
>>> check = []
>>> for item in result:
>>> check.append(isinstace(item, DjangoProject.itemModel.SomeProperty))
But Python is much more expressive, and we can use lambda functions and some
functional programming, to this:
>>> map(lambda x: isinstance(x, DjangoProject.itemModel.SomeProperty), result)
[True, True, True]
And even more cool is this:
>>>all(map(lambda x: isinstance(x, DjangoProject.itemModel.SomeProperty), result))
TrueWritten by Oz
Related protips
2 Responses
A couple things here:
What are you actually trying to achieve? If you're trying to determine which subset of a list is of the type that you're looking for, wouldn't it make more sense to use
filter? (Might not be what you're doing, but I've seen that logic applied before, which makes me cringe).-
It would also be worthwhile noting that
isinstancewill also yieldTruefor instances that subclass a given class:In [1]: isinstance('asd', basestring)
Out[1]: True
In [2]: type('asd') == basestring
Out[2]: False
Hi Demian,
You are right, filter is also usable here:
filter(lambda x: isinstance(x, DjangoProject.itemModel.SomeProperty), result)
However, filter will return the list result itself, clean of unwanted items. Which for me was not possible. I wanted to have 'all or nothing', that is why I used the combination of all and map.