Stop Writing Blind Wrappers: How to Properly Type Your Python Wrapping Code
Blog post from Mergify
Python's flexible nature allows for elegantly wrapping functions and classes, but doing so without proper type annotations can introduce errors that are hard to debug. Using type hints with tools like Mypy, developers should avoid using *args: Any and **kwargs: Any in wrappers, as they disable effective type checking and allow errors to surface only at runtime. Common fixes using ParamSpec are insufficient for simple wrappers, as it is designed for decorators and higher-order functions. Instead, the recommended approach is to use functools.partial, which maintains the function's signature and enables Mypy to catch errors during type checking, thus ensuring strong type safety. Embracing these practices improves maintainability, reduces runtime errors, and enhances the overall developer experience by aligning with Python's evolving type system.