Last updated: Apr 10, 2024
Reading timeยท3 min
The "TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union" occurs for 2 main reasons:
list
.isinstance()
Here is an example of how the error occurs.
a_list = [str, int, bool] # โ๏ธ TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union result = isinstance('bobbyhadz.com', a_list)
We passed a list as the second argument to the isinstance()
function which
caused the error.
The isinstance
function can either be passed a class or a tuple of classes.
isinstance()
functionYou can use the tuple() class to convert the list to a tuple if you are trying to check if an object is an instance of one of multiple classes.
a_list = [str, int, bool] result = isinstance('bobbyhadz.com', tuple(a_list)) print(result) # ๐๏ธ True
The isinstance() function
returns True
if the passed-in object is an instance or a subclass of the
passed-in class or at least one of the classes in a tuple.
The error is also caused if you shadow a built-in class by declaring a variable with the same name.
# ๐๏ธ This shadows the built-in list class list = ['bobby', 'hadz', 'com'] numbers = [1, 2, 3] # โ๏ธ TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union result = isinstance(numbers, list)
We declared a variable named list which shadows the built-in list
class.
isinstance()
function rather than the built-in list
class.To solve the error, rename the variable in your code.
a_list = ['bobby', 'hadz', 'com'] numbers = [1, 2, 3] result = isinstance(numbers, list) print(result) # ๐๏ธ True
We renamed the variable to a_list
, so it no longer shadows the built-in list
class.
type()
class to get around the errorIf you aren't able to rename the variable, use the type()
class.
list = ['bobby', 'hadz', 'com'] numbers = [1, 2, 3] result = isinstance(numbers, type(list)) print(result) # ๐๏ธ True
The type class returns the type of an object.
print(type(['bobby', 'hadz', 'com'])) # ๐๏ธ <class 'list'> print(type('bobbyhadz.com')) # ๐๏ธ <class 'str'>
Most commonly the return value is the same as accessing the __class__
attribute on the object.
You can also pass an object of the correct type to the type()
class, it
doesn't have to be the variable that shadows the built-in class.
list = ['bobby', 'hadz', 'com'] numbers = [1, 2, 3] result = isinstance(numbers, type([])) print(result) # ๐๏ธ True
However, the best solution is to rename the variable in your code to something that doesn't shadow a built-in Python class.
To solve the "TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union":
isinstance()
function.You can learn more about the related topics by checking out the following tutorials: