Practical Applications
1. Dynamic Type Checking
def validate_input(data, expected_type):
if not isinstance(data, expected_type):
raise TypeError(f"Expected {expected_type}, got {type(data)}")
def process_data(data):
validate_input(data, list)
return [x * 2 for x in data]
## LabEx Python Tutorial Example
try:
result = process_data([1, 2, 3])
print(result)
## This will raise a TypeError
process_data("not a list")
except TypeError as e:
print(f"Validation Error: {e}")
2. Automatic Serialization
import json
class DataSerializer:
@staticmethod
def serialize(obj):
return json.dumps({
'type': type(obj).__name__,
'data': obj,
'metadata': {
'length': len(obj) if hasattr(obj, '__len__') else None
}
})
## Example usage
data = [1, 2, 3, 4, 5]
serialized = DataSerializer.serialize(data)
print(serialized)
Attribute Exploration
def explore_object_capabilities(obj):
capabilities = {
'attributes': [attr for attr in dir(obj) if not attr.startswith('__')],
'methods': [method for method in dir(obj) if callable(getattr(obj, method))]
}
return capabilities
## LabEx demonstration
example_list = [1, 2, 3]
print(explore_object_capabilities(example_list))
Pattern |
Description |
Use Case |
Type Validation |
Check input types |
Data processing |
Dynamic Dispatch |
Select methods based on type |
Polymorphic behavior |
Serialization |
Convert objects to portable format |
Data storage/transfer |
graph TD
A[Input Data] --> B{Type Checking}
B -->|Valid| C[Process Data]
B -->|Invalid| D[Raise Exception]
C --> E[Serialize/Transform]
E --> F[Output/Storage]
3. Automated Documentation Generation
def generate_function_doc(func):
return {
'name': func.__name__,
'docstring': func.__doc__,
'arguments': func.__code__.co_varnames[:func.__code__.co_argcount],
'line_count': func.__code__.co_firstlineno
}
def calculate_area(radius):
"""Calculate the area of a circle."""
return 3.14 * radius ** 2
doc_metadata = generate_function_doc(calculate_area)
print(doc_metadata)
- Reflection
- Runtime type checking
- Automatic interface validation
- Dynamic code generation
Metadata provides powerful tools for creating flexible, robust Python applications by enabling runtime introspection and dynamic behavior.