isinstance()
isinstance(obj, cls) asks whether an object is an instance of a class or any subclass of it; issubclass does the same for two classes.
In more detail
Prefer isinstance to comparing type(obj) == cls, because it respects inheritance. Checking types this way is best kept to the edges of a program, where outside data comes in.
Related terms
- inheritance — Declaring one class or type as a specialised version of another, so it receives the parent's members and can be used wherever the parent is expected.
- class — A blueprint in code that bundles data and the functions that work on it, from which objects are made.
- data type — The kind of a value, such as a whole number, text or a date, which decides what you can do with it and how it compares and sorts.
Taught in
- Structured Output — AI Engineering: LLM Apps, RAG & Agents
- Raising, And Writing Your Own Exception — Hands-on Python: Complete Video Course & Book
- Classes And Instances — Hands-on Python: Complete Video Course & Book
- Inheritance And Composition — Hands-on Python: Complete Video Course & Book
- The Exception Family Tree — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Import Variants, dir() And sys.path — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Exception Classes Of Your Own — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Exceptions Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Classes, Objects And Two Stacks — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Introspection: hasattr, __name__, __module__ And __bases__ — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Inheritance, super() And Polymorphism — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Multiple Inheritance, The MRO And Diamonds — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Object-Oriented Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- read, readline, errno And bytearray — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Mock, Review And Exam Day — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep