getsentry / getsentry/sentry-python

Replace `ClientConstructor` with a `TypedDict`

未关闭
#2,820 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
Component: DX Improvement Python
主要语言
Python
星标
2.2k
派生
669
平均合并
1 天 1 小时
30 天内合并 PR
213

描述

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 `mypy` with hacky workarounds.
- `mypy` enforces the `**kwargs`'s types within `Client.__init__`. Currently, `**kwargs` is recognized as a `dict[str, Any]`, which is type-unsafe.
- `mypy` currently incorrectly recognizes the arguments in `ClientConstructor` as all being valid positional arguments, when in reality, only the `dsn` may be provided as a positional argument. Providing any other arguments as positional arguments [results in a `TypeError`](https://github.com/getsentry/sentry-python/blob/16d25e20098583833d4e7827fcd76ad0940e0f2c/sentry_sdk/client.py#L86-L87). With a `TypedDict`, `mypy` is 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`.

贡献指南

打开贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。