How do I check if a variable is of a specific type in Python?
Gable E
gable e profile pic

In Python, you can check if a variable is of a specific type using theisinstance() function. Theisinstance() function allows you to determine if an object is an instance of a specified class or its subclasses. Here's an example of how you can perform this check:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# Example 1: Check if variable is of a specific type
my_var = 42

if isinstance(my_var, int):
    print("my_var is an integer.")
else:
    print("my_var is not an integer.")

# Example 2: Check if variable is of any type in a list of types
my_var = "Hello"

if isinstance(my_var, (int, str, list)):
    print("my_var is an integer, string, or list.")
else:
    print("my_var is not an integer, string, or list.")

In the above code, theisinstance() function is used to check ifmy_var is an instance of a specific type. In the first example, it checks ifmy_var is an instance of theint class. If it is, the code block inside theif statement is executed, printing "my_var is an integer." Otherwise, the code block inside theelse statement is executed, printing "my_var is not an integer." In the second example, theisinstance() function is used to check ifmy_var is an instance of any type in a tuple of types(int, str, list). If it is, the code block inside theif statement is executed, printing "my_var is an integer, string, or list." Otherwise, the code block inside theelse statement is executed, printing "my_var is not an integer, string, or list." You can use theisinstance() function by providing the object and the class (or tuple of classes) to check against as arguments. It will returnTrue if the object is an instance of the specified class or any of its subclasses. Otherwise, it will returnFalse. Theisinstance() function is useful when you need to determine the type of an object dynamically or perform conditional checks based on the object's type. It allows you to write flexible and reusable code that can handle different object types appropriately.