Built-in Type Verification Functions
type() Function
The primary method for checking object types in Python.
## Basic type checking
x = 42
print(type(x)) ## <class 'int'>
y = "LabEx"
print(type(y)) ## <class 'str'>
graph TD
A[Type Verification Tools] --> B[Built-in Functions]
A --> C[Type Checking Methods]
B --> D[type()]
B --> E[isinstance()]
C --> F[Isinstance Check]
C --> G[Type Comparison]
isinstance() Function
Checks if an object is an instance of a specific class or type.
## Checking multiple types
def process_data(value):
if isinstance(value, (int, float)):
return value * 2
elif isinstance(value, str):
return value.upper()
else:
return None
Advanced Type Verification Techniques
Type Checking with Collections
Method |
Description |
Example |
all() |
Check if all elements match type |
all(isinstance(x, int) for x in [1,2,3]) |
any() |
Check if any element matches type |
any(isinstance(x, str) for x in [1,'a',3]) |
Type Annotations and Checking
from typing import List, Union
def validate_input(data: List[Union[int, str]]) -> bool:
return all(isinstance(item, (int, str)) for item in data)
## LabEx example
test_data = [1, 'hello', 2, 'world']
print(validate_input(test_data)) ## True
mypy Static Type Checker
## Install mypy
pip install mypy
## Run type checking
mypy your_script.py
Runtime Type Checking
def strict_type_check(value: int) -> int:
if not isinstance(value, int):
raise TypeError(f"Expected int, got {type(value)}")
return value
try:
result = strict_type_check("not an int")
except TypeError as e:
print(e)
Best Practices
- Use
isinstance()
for flexible type checking
- Leverage type annotations
- Implement runtime type validation
- Use static type checkers for additional safety
Comparison of Type Verification Methods
Method |
Use Case |
Performance |
Flexibility |
type() |
Exact type check |
Fast |
Low |
isinstance() |
Inheritance check |
Moderate |
High |
Type Annotations |
Static checking |
Compile-time |
Moderate |
Error Handling and Type Verification
def safe_convert(value, target_type):
try:
return target_type(value)
except (ValueError, TypeError):
print(f"Cannot convert {value} to {target_type}")
return None
## LabEx safe conversion example
result = safe_convert("42", int) ## Successful
result = safe_convert("hello", int) ## Handles error