isinstance()
isinstance(x, T) answers True or False: is x of type T (or of a subclass of T)?
Used in 35 lessons of the course, from 00.05.
isinstance(obj, cls) returns True if the object is an instance of that class, or of any subclass of it. Otherwise it returns False.
It reads almost like a sentence: "is error an AuthenticationError?". That is why it sits so often inside an if.
It also accepts a tuple of classes: isinstance(x, (int, float)) is True if x is either one.
Prefer it over type(x) == T. type() demands the exact type and rejects subclasses. isinstance() accepts them, which is usually what you want.
In the course you see it in if isinstance(error, groq.AuthenticationError):. A variable can hold errors of several classes, and this line decides what to do depending on which one it is.
Reach for it when: a value can be of several types and your code must act differently depending on which one it is, for example when checking which error arrived.
Examples
Common mistake
print(isinstance(5, "int"))
Why: The second argument must be a class (or a tuple of classes), not a string with its name.
How to write it: Write the class without quotes: isinstance(5, int).
Common mistake
print(isinstance(True, int))
Why: bool is a subclass of int, so True counts as an int. It can surprise you when validating numbers.
How to write it: If you don't want booleans, check first: isinstance(x, int) and not isinstance(x, bool).
