Master Python’s isinstance(): Core Syntax, Examples, and 10 API Testing Scenarios
This guide explains Python’s built‑in isinstance() function, shows its basic syntax and usage—including single‑type, multiple‑type, and inheritance checks—and provides ten practical API‑testing scenarios with ready‑to‑run code examples.
What is isinstance() ?
isinstance()is a built‑in Python function that checks whether an object is an instance of a specified type or a subclass thereof. It is especially useful when handling inputs of various types or when a program must enforce specific type constraints.
Syntax
isinstance(object, classinfo)object : the value to be checked.
classinfo : a type or a tuple of types that defines the allowed types.
Basic usage examples
Check a single type
x = 5
if isinstance(x, int):
print("x is an integer")
else:
print("x is not an integer")Check multiple types
y = 5.0
if isinstance(y, (int, float)):
print("y is an integer or float")
else:
print("y is not an integer or float")Check inheritance relationship
class Animal: pass
class Dog(Animal): pass
class Cat(Animal): pass
my_pet = Dog()
if isinstance(my_pet, Animal):
print("my_pet is an instance of Animal or its subclass")Important notes
When classinfo is a tuple, isinstance() returns True if the object matches any type in the tuple.
For user‑defined classes that inherit from other classes, isinstance() also considers the inheritance chain.
Using isinstance() helps manage Python’s dynamic typing, improving code flexibility and robustness.
10 practical scenarios for API test automation
Validate response status code is an integer
response_status = 200
assert isinstance(response_status, int), "Status code should be an integer"Check response body is a dictionary
response_body = {'message': '成功'}
assert isinstance(response_body, dict), "Response body should be a dict"Confirm request parameter is a string
param = "exampleParam"
assert isinstance(param, str), "Request parameter should be a string"Validate date‑time field is a string
date_str = "2023-04-28T12:00:00Z"
assert isinstance(date_str, str), "Date‑time should be a string"Check numeric field (int or float)
amount = 100.50
assert isinstance(amount, (int, float)), "Amount should be int or float"Confirm list‑type data
items_list = ["item1", "item2"]
assert isinstance(items_list, list), "Data should be a list"Dictionary key‑value type check
data = {'price': 99.99}
assert isinstance(data.get('price'), float), "Price should be a float"Validate boolean flag
isActive = True
assert isinstance(isActive, bool), "Active flag should be boolean"Check for NoneType
optionalField = None
assert isinstance(optionalField, type(None)), "Field may be None"Custom type verification
class User:
def __init__(self, name, age):
self.name = name
self.age = age
user_instance = User("Alice", 30)
assert isinstance(user_instance, User), "Returned user should be an instance of User"These scenarios demonstrate how isinstance() can be leveraged in API automation tests to enforce data‑type consistency, thereby enhancing test robustness and accuracy.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
