sentry-python
sentry-python copied to clipboard
Replace `ClientConstructor` with a `TypedDict`
We currently use ClientConstructor to trick mypy (and other static analyzers) into believing that Client.__init__ takes many typed parameters, rather than untyped **kwargs. The current solution is somewhat hacky, as it separates the Client class's actual implementation into a separate _Client class.
We could instead define a TypedDict with the parameters accepted in Client.__init__'s **kwargs, and type the **kwargs with this TypedDict. I have already implemented similar functionality for start_transaction in https://github.com/getsentry/sentry-python/pull/2796.
Advantages of switching to a TypedDict include:
- Code is clearer, since we are not fooling
mypywith hacky workarounds. mypyenforces the**kwargs's types withinClient.__init__. Currently,**kwargsis recognized as adict[str, Any], which is type-unsafe.mypycurrently incorrectly recognizes the arguments inClientConstructoras all being valid positional arguments, when in reality, only thedsnmay be provided as a positional argument. Providing any other arguments as positional arguments results in aTypeError. With aTypedDict,mypyis aware that the arguments must be passed as keyword arguments.
Disadvantages of switching to a TypedDict:
- The current solution allows us to indicate the default value's of the arguments, when they are not provided. Specifying default values may not be possible with a
TypedDict.