πΉ What is Type Checking?
Type checking is the process of checking the data type of a value or variable. Python provides several ways to do this.
age = 17
name = "Ted"
skills = ["Python", "AI", "Data Science"]
print(type(age)) # <class 'int'>
print(type(name)) # <class 'str'>
print(type(skills)) # <class 'list'>
πΉ Using
isinstance()isinstance() is often more useful when you want to check whether a value belongs to a particular type.age = 17
if isinstance(age, int):
print("Age is an integer")
πΉ Type Hints
Python also supports type hints, which make your code easier to understand and allow tools such as IDEs and static type checkers to detect potential problems.
def calculate_total(price: float, quantity: int) -> float:
return price * quantity
Here:
price: float β expected to be a decimal numberquantity: int β expected to be an integer-> float β expected return typeπ Key takeaway:
Python is dynamically typed, but that doesn't mean you should ignore types. Using
type(), isinstance(), and type hints can make your Python code more reliable and easier to maintain.