Talks - Koudai Aono: Enhancing Decorators with Type Annotations: Techniques and Best Practices

Koudai Aono

Learn how to leverage Python 3.12's new decorator type annotations for better type safety, improved code clarity, and enhanced static analysis in your codebase.

Key takeaways
  • Python 3.12 introduces new syntax for type annotations in decorators, allowing cleaner type definitions without extra imports

  • ParamSpec is a powerful feature for defining keyword and positional arguments in decorator typing, using P.args and P.kwargs

  • Type protocols can be used to define interfaces for typing, especially useful when dealing with similar but not identical objects (like different HTTP client responses)

  • The * operator in function signatures can enforce keyword-only arguments, helping prevent runtime errors and improve code clarity

  • Using generics with decorators (like T and R) helps maintain proper typing for function arguments and return values

  • The new type syntax reduces the need for explicit typing imports and makes code more readable by allowing inline type definitions

  • Decorators can inject arguments (like loggers) as the first parameter while maintaining proper type checking

  • The Callable type combined with ParamSpec provides better type hints for decorated functions compared to using Any

  • Python 3.12’s type system improvements help detect keyword argument misuse at compile time rather than runtime

  • Modern type checkers like MyPy and Pyright can validate decorator types more effectively with these new annotations