- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What's the canonical way to check for type in python?
If you want to check if an object, x is an instance of exactly a given type(not a subtype), you can use typeto get its type and check using is statement.
example
x = "Hello" if type(x) is str: print("x is an instance of str")
Output
This will give the output
x is an instance of str
If you want to check if x is an instance of a MyClass or any subclass of MyClass, you can use the isinstance method call.
example
x = "Hello" if isinstance(x, str): print("x is an instance of str")
Output
This will give the output
x is an instance of str
Advertisements