Assert isinstance Python

assert isinstance() is a Python statement that allows you to check if a variable is an instance of a specified type and raise an exception if it is not. It is often used in unit tests to ensure that a function is being called with the correct type of arguments.

Here’s an example of how to use assert isinstance():

def my_function(arg):
    assert isinstance(arg, str), "arg must be a string"
    print("arg is a string")

my_function("hello")  # prints "arg is a string"
my_function(123)  # raises AssertionError: arg must be a string

In this example, my_function() expects a string as its argument. If it is called with a string, it will print “arg is a string”. If it is called with any other type of argument, it will raise an AssertionError with the message “arg must be a string”.

assert isinstance() takes two arguments: the variable you want to check, and the type you want to check it against. If the variable is an instance of the specified type, assert isinstance() does nothing. If it is not, it raises an AssertionError with an optional message.

You can also use assert isinstance() to check if a variable is an instance of a subclass of the specified type by setting the issubclass keyword argument to True. For example:

class MyString(str):
    pass

def my_function(arg):
    assert isinstance(arg, str, issubclass=True), "arg must be a string or a subclass of str"
    print("arg is a string or a subclass of str")

my_function("hello")  # prints "arg is a string or a subclass of str"
my_function(MyString("hello"))  # prints "arg is a string or a subclass of str"
my_function(123)  # raises AssertionError: arg must be a string or a subclass of str

In this example, my_function() expects a string or a subclass of str as its argument. If it is called with a string or a subclass of str, it will print “arg is a string or a subclass of str”. If it is called with any other type of argument, it will raise an AssertionError with the message “arg must be a string or a subclass of str”.

Leave a Comment