Welcome, guest | Sign In | My Account | Store | Cart

So it turned out that I needed a way of ensuring that all members of an iterable are instances of a certain class. Here, therefore, is the isallinstance() function.

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def isallinstance(iterable, typeOrTuple):
    return all(isinstance(i, typeOrTuple) for i in iterable)




## Previous Version:
##
## def isallinstance(iterable, typeOrTuple):
##     vals = [isinstance(i, typeOrTuple) for i in iterable]
##     return len(vals) == sum(vals)

2 comments

Stephen Chappell 11 years, 9 months ago  # | flag

How about this version written for Python 3?

def isallinstance(iterable, class_or_type_or_tuple) -> bool:
    return all(isinstance(item, class_or_type_or_tuple) for item in iterable)
Jonathan Frere (author) 11 years, 9 months ago  # | flag

I've never seen the all() code before, but fiddling around suggests it's been around since 2.5, which makes it worrying that I've never noticed it before. Thanks.

Created by Jonathan Frere on Thu, 26 Jul 2012 (MIT)
Python recipes (4591)
Jonathan Frere's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks