MSeifert
MSeifert

Reputation: 152840

isinstance check if any of the variables has a certain class

I'm having a function that needs to take a different route if any of the parameters is a np.ndarray. I'm checking with isinstance. But I wondered if there might be a more intuitive (and faster) way than using a list comprehension together with any:

def func(a, b):
    if any([isinstance(i, np.ndarray) for i in [a, b]]):
        ...
    else:
        ...

I already tried:

if isinstance([a, b], np.ndarray):

but that doesn't work because [a, b] is a list ...

Upvotes: 2

Views: 1032

Answers (1)

Kasravnd
Kasravnd

Reputation: 107347

Actually using any is the most pythonic way because it has been implemented in python like following:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

And will return True right after encounter a True item in your iterable thus it's order in best case would be O(1) and in worst case O(n). And about the isinstance() it's a built in function and is a pythonic way for checking the objects type.

Also as a more pythonic way you better to pass a generator expression to any and let generator function generate the items on demand, instead of a list comprehension and create all the boolean values at once.:

any(isinstance(i, np.ndarray) for i in [a, b])

As @Padraic said if you are only dealing with two item the best way is using or operator:

if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):
           # do stuff

Upvotes: 3

Related Questions