Table of Contents | |
Understanding Python isinstance()
Function
The isinstance() function in Python is a built-in function that checks if an object is an instance of a particular class or type. This is crucial for type checking and ensuring that your code works with the kinds of objects it expects. You provide the object, and the class (or a tuple of classes) and Python isinstance() returns True
or False
. It also considers inheritance.
Syntax of Python isinstance()
result = isinstance(object, classinfo)
Explanation
result
: Variable stores boolean whichisinstance
return.isinstance()
: Built-in function for type checking.object
: Object you’re checking.classinfo
: Class, type, or tuple of classes/types.
Example of Python isinstance()
my_number = 5
is_int = isinstance(my_number, int)
print(is_int)
Explanation
my_number = 5
: Assigns integer 5 to a variable.is_int = isinstance(my_number, int)
: Checksmy_number
is instance ofint
.print(is_int)
: Prints returned value.
Output
True
isinstance()
Parameters
The isinstance() function takes two parameters. The first parameter is the object you want to check. The second parameter, classinfo
, specifies the type, class, or a tuple of types and/or classes you’re checking against. If you provide a tuple for the second parameter, Python isinstance() returns True
if the object is an instance of any of the types or classes in that tuple. Otherwise, the function will return False
.
Syntax
boolean_result = isinstance(object_to_check, type_or_class_or_tuple)
Explanation
boolean_result
: StoresTrue
orFalse
.isinstance()
: Checks the object’s type.object_to_check
: The object.type_or_class_or_tuple
: Single type/class, or tuple of types/classes.
Example
my_string = "hello"
result = isinstance(my_string, (str, int))
print(result)
Explanation
my_string = "hello"
: String variable.result = isinstance(my_string, (str, int))
: Checks if string is an instance of eitherstr
orint
.print(result)
: Prints the returned value.
Output
True
isinstance()
Return Value
Python isinstance() function provides a boolean value: True
or False
. It returns True
if the provided object is an instance of the specified class or type (or one of the classes/types if a tuple is provided). If the object is not an instance of any specified types or classes, it returns False
. It also considers inheritance.
Syntax
true_or_false = isinstance(some_object, some_class)
Explanation
true_or_false
: Holds the boolean result.isinstance()
: Performs the instance check.some_object
: Object you want to check.some_class
: Class, type, or tuple of classes/types.
Example
my_list = [1, 2, 3]
is_list = isinstance(my_list, list)
print(is_list)
Explanation
my_list = [1, 2, 3]
: List variable.is_list = isinstance(my_list, list)
: Checksmy_list
is instance oflist
.print(is_list)
: Displays output.
Output
True
Native Types with Python isinstance()
A common use of Python isinstance() is checking against Python’s native data types. You can verify if a variable holds a string, integer, float, list, dictionary, or any other built-in type. This allows you to write code that handles different data types differently. If your function expects a list, you can use isinstance()
to ensure the provided argument is a list before your code attempts list-specific operations.
Syntax
check_result = isinstance(variable, native_type)
Explanation
check_result
: Will store boolean.isinstance()
: Checks for type.variable
: Object which type to be checked.native_type
: Built-in type likeint
,str
,list
,dict
,float
.
Example
data = 10.5
is_float = isinstance(data, float)
print(is_float)
Explanation
data = 10.5
: Assigns floating value.is_float = isinstance(data, float)
: Checkdata
is instance offloat
.print(is_float)
: Prints result.
Output
True
Int and List with Python isinstance()
Combining checks for int
and list
with Python isinstance() allows you to handle cases where you might accept either type. You can provide a tuple containing both int and list as the second argument to isinstance()
. This flexibility lets you create more adaptable functions that can process individual integers or entire lists of integers, depending on what’s provided.
Syntax
is_int_or_list = isinstance(input_data, (int, list))
Explanation
is_int_or_list
: Stores boolean result.isinstance()
: Performs check.input_data
: Object which type to be checked.(int, list)
: Checks instance of eitherint
orlist
.
Example
value = 25
result = isinstance(value, (int, list))
print(result)
Explanation
value = 25
: Assigns integer value.result = isinstance(value, (int, list))
: Checks thevalue
is instance ofint
orlist
.print(result)
: Prints the returned value.
Output
True
Objects with Python isinstance()
When working with object-oriented programming in Python, isinstance()
is your go-to tool for verifying object types. You can check if an object is an instance of a specific class you’ve defined. It also checks for an inheritance; if you have a class hierarchy, Python isinstance() will return True
if the object is an instance of the specified class or any of its parent classes.
Syntax
is_instance = isinstance(my_object, MyClass)
Explanation
is_instance
: Holds theTrue
orFalse
outcome.isinstance()
: Built-in function for type checking.my_object
: Object you’re checking.MyClass
: The class.
Example
class Animal:
pass
class Dog(Animal):
pass
my_dog = Dog()
result = isinstance(my_dog, Animal)
print(result)
Explanation
class Animal:
: Defines base class.class Dog(Animal):
:Dog
class inherits fromAnimal
.my_dog = Dog()
: Creates an object.result = isinstance(my_dog, Animal)
: Checks object is instance of the class.print(result)
: DisplaysTrue
because of inheritance.
Output
True
String with Python isinstance()
Checking if a variable holds a string is very common, and Python isinstance() makes it simple. You would use str
as the second argument to isinstance()
. This is crucial for data validation, ensuring a function receives string input before attempting string operations.
Syntax
is_string = isinstance(variable,str)
Explanation
is_string
: Stores returned value.isinstance()
: Function to check if instance of a class.variable
: Which is needed to be checked.str
: Built-in type.
Example
text = "Sample string"
result = isinstance(text, str)
print(result)
Explanation
text
: Variable of string type.result
: Stores the boolean result ofisinstance(text, str)
.print(result)
: OutputsTrue
.
Output
True
Dictionary with Python isinstance()
Using isinstance()
to identify dictionaries is similar to how you use it to check other datatypes. Pass in the variable and dict
class as the second parameter. The method will return True
if the variable is an instance of dict
; otherwise, it returns False
.
Syntax
is_dictionary = isinstance(variable,dict)
Explanation
is_dictionary
: Holds return value.isinstance()
: Checks the variable for dictionary type.variable
: Represents data which is needed to be checked.dict
: Keyword for dictionary.
Example
data = {"name": "Alice", "age": 30}
check = isinstance(data, dict)
print(check)
Explanation
data
: Defined dictionary.check = isinstance(data, dict)
: Verifies ifdata
is a dictionary.print(check)
: Output the result (True
).
Output
True
Class Methods with Python isinstance()
Within a class, you might have methods that need to behave differently depending on the type of object they receive as input. Python isinstance() is used inside a method to check the type of an argument. This is a form of conditional logic, You can tailor the method’s behavior based on whether it’s dealing with, say, a string, a list, or an instance of another class.
Syntax
class MyClass:
def process_data(self, data):
if isinstance(data, SomeType):
# Do something specific to SomeType
pass
Explanation
class MyClass:
: Declares class.def process_data(self, data):
: Method which takes inputdata
.if isinstance(data, SomeType):
: Checks type of the object passed as a parameter.pass
: Placeholder for specific handling.
Example
class Processor:
def process(self, item):
if isinstance(item, str):
print("Processing string:", item.upper())
elif isinstance(item, int):
print("Processing integer:", item * 2)
processor = Processor()
processor.process("hello")
processor.process(5)
Explanation
class Processor:
: DefinesProcessor
class.def process(self, item):
:process
method that takes parameter.if isinstance(item, str):
: Checks ifitem
is a string.print("Processing string:", item.upper())
: If string, converts to uppercase and prints.elif isinstance(item, int):
: Checks ifitem
is integer.print("Processing integer:", item * 2)
: If it is integer, multiply by 2 and prints.processor = Processor()
: Creates instance of class.processor.process("hello")
: Callsprocess
with string.processor.process(5)
: Callsprocess
with integer.
Output
Processing string: HELLO
Processing integer: 10
Difference between isinstance()
and type()
Methods in Python
Both isinstance()
and type()
can be used to check a variable’s type. type()
returns the exact type of an object, while isinstance()
checks if an object is an instance of a class or its parent classes. Therefore, isinstance()
is generally preferred because it handles inheritance correctly. Use type()
only when you need to check for the exact type, not any subclasses.
Syntax
# isinstance() – Preferred for most cases
isinstance(object, class_or_type)
# type() – For strict type equality
type(object) is ExactType
Explanation
isinstance(object, class_or_type)
: Checks inheritance.type(object) is ExactType
: Checks for exact type match, not considering inheritance.
Example
class Parent:
pass
class Child(Parent):
pass
obj = Child()
print(isinstance(obj, Parent)) # Using isinstance()
print(type(obj) is Parent) # Using type()
Explanation
class Parent:
: Defines class.class Child(Parent):
: Inherits fromParent
.obj = Child()
: Creates aChild
object.print(isinstance(obj, Parent))
: Checks instance considering inheritance.print(type(obj) is Parent)
: Checks for exact type match.
Output
True
False
Conclusion
Python isinstance() is a built-in function in Python. It takes two parameters: the object and class info. Python isinstance returns True
if the object is an instance of the provided class info; otherwise, it returns False
. It is better to use isinstance()
than type()
as isinstance()
considers inheritance.