When writing Python code with type annotations:
- Use
Any
from the typing module instead of implementation-specific types like csv.writer
- Create custom TypedDict classes to define structure of dictionary data
- Use
cast()
from typing module to properly annotate values from external sources or when changing type
- Add null/None checks before accessing potentially None values
- Be explicit about return types and ensure all return paths match the declared type
- For dictionary values with complex structures, define custom types rather than using nested Dict[str, Any]
- For collections of objects with defined structures, use specific types rather than generic Dict or List
- Be careful with Optional types - only use cast to remove Optional when you've verified value is not None
- Add proper type annotations for function parameters and return values
- When using TypeVars, define them at the module level with clear constraints