Generally (i.e. I haven't found any counter examples) in python isinstance()
is preferred over type()
because of checking inheritance, speed and/or seemingly neater look. Let's investigate a provocative example. Knowing that bool
is a subclass of int
, let's say that we want to check if an object is an instance of a class, but not its subclasses. The motivation behind doing so is that while checking/using subclasses might not be a problem in python (maybe?), it may cause problems when python interacts with external tools (for example in other languages bool
is not necessarily a subclass of int
). I see two options of performing such check:
if isinstance(var, int) and not isinstance(var, bool): ...
or
if type(var) is int: ...
and personally it looks like using type
is a neater approach here. Also in case in the future we subclass int
even more, type
check would be easier to maintain.
The question is if this might be the case of using type
over isinstance
? Going one step even further: should we use type
over isinstance
in the case when we want to check if an object is of a particular class not including its subclasses. Any concerns?
PS If anyone's interested, the speed of both validations are almost identical with validation by type
usually being a little faster. With the code:
import time
class Timer:
def __init__(self):
self.start_time = None
def __enter__(self):
self.start_time = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"Total time taken: {round(time.time() - self.start_time, 3)}")
self.start_time = None
def validate_isinstance(var):
return isinstance(var, int) and not isinstance(var, bool)
def validate_type(var):
return type(var) is int
for validation_method in (validate_isinstance, validate_type):
with Timer():
for _ in range(10**6):
validate_isinstance(True)
I get:
Total time taken: 0.236
Total time taken: 0.226