Advanced Type Techniques
Protocol Classes
from typing import Protocol, runtime_checkable
@runtime_checkable
class Drawable(Protocol):
def draw(self) -> None:
...
class Circle:
def draw(self) -> None:
print("Drawing a circle")
class Square:
def draw(self) -> None:
print("Drawing a square")
def render(obj: Drawable) -> None:
obj.draw()
Type Hint Advanced Patterns
Technique |
Description |
Use Case |
Literal Types |
Restrict to specific values |
Configuration options |
TypedDict |
Structured dictionary types |
API responses |
Final |
Prevent inheritance/modification |
Constant classes |
NewType |
Create distinct type aliases |
Domain-specific types |
Sophisticated Type Inference
from typing import TypeVar, Callable, Any
T = TypeVar('T')
R = TypeVar('R')
def retry(
attempts: int = 3,
exception_type: type[Exception] = Exception
) -> Callable[[Callable[..., T]], Callable[..., T]]:
def decorator(func: Callable[..., T]) -> Callable[..., T]:
def wrapper(*args: Any, **kwargs: Any) -> T:
for _ in range(attempts):
try:
return func(*args, **kwargs)
except exception_type:
continue
raise RuntimeError("Max attempts exceeded")
return wrapper
return decorator
Type System Workflow
graph TD
A[Type Annotation] --> B[Static Type Checking]
B --> C{Type Errors?}
C -->|Yes| D[Refactor Code]
C -->|No| E[Runtime Execution]
E --> F[Dynamic Type Handling]
Conditional Type Hints
from typing import TypeVar, Conditional, reveal_type
T = TypeVar('T')
def conditional_process(value: T) -> Conditional[T, bool]:
if isinstance(value, bool):
return value
return str(value)
## Demonstrates type-aware conditional processing
Advanced Generic Techniques
from typing import Generic, TypeVar, Sequence
T = TypeVar('T')
U = TypeVar('U')
class Transformer(Generic[T, U]):
def __init__(self, data: Sequence[T]):
self._data = data
def transform(self, func: Callable[[T], U]) -> list[U]:
return [func(item) for item in self._data]
Type Checking Strategies
- Use mypy for static analysis
- Implement runtime type checking
- Leverage type stub files
- Create custom type validators
- Minimal runtime overhead
- Use
typing.cast()
for type conversions
- Optimize type checking in critical paths
LabEx Development Patterns
- Implement comprehensive type annotations
- Use type hints in library design
- Create reusable type checking utilities
- Document complex type signatures
Emerging Type System Features
- Gradual typing support
- Enhanced static analysis
- Better IDE integration
- Cross-language type compatibility
By mastering these advanced type techniques, Python developers can create more robust, type-safe, and maintainable code, especially in complex projects developed on platforms like LabEx.