0

I want to check that the type of four variables is a particular type, and I have to do:

if (type(a) is not SomeType or
    type(b) is not SomeType or
    type(c) is not SomeType or
    type(d) is not SomeType):
    raise Exception("Not the correct types")

This feels repetitive. It seems there could be a better, less redundant way of doing this?

XYZT
  • 605
  • 5
  • 17

1 Answers1

3

You can use any to check if any of the items are of type SomeType.

You should also consider using isinstance to check for types.

if any(not isinstance(item, SomeType) for item in [a,b,c,d]):
    raise Exception("Not the correct types")

You can also write this using all

if not all(isinstance(item, SomeType) for item in [a,b,c,d]):
    raise Exception("Not the correct types")
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
  • 1
    The parameters to `isinstance` are backwards, and in addition it should be `any(not ...)`. Also note that `type(x) is A` is not exactly the same as `instance(x, A)` as the latter also allows derived types (though `isinstance` is usually better). – interjay Jun 25 '19 at 15:31
  • For me this is more readable: `if not all(isinstance(item, SomeType) for item in [a,b,c,d]):` – Matthias Jun 25 '19 at 17:24