Callable with variadic fixed arguments that doesn't mean *args
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 1.8k
- 派生
- 302
- 平均合并
- 23 小时
- 30 天内合并 PR
- 8
描述
Suppose I have a type of function called CommandHandler, that is a function that receives a command as its first parameter but then could have other parameters.
Examples
class Command:
pass
class RegisterUser(Command):
pass
class DeleteUser(Command):
pass
def register_user(command: RegisterUser, db : Db) -> None:
...
def delete_user(command: DeleteUser, dispatch: EventDispatcher, cache: Cache) -> None:
...
mappings : dict[Command, CommandHandler] = {
RegisterUser: register_user,
DeleteUser: delete_user
}
What would be the definition of CommandHandler?
Ideally it would be:
C= TypeVar("C", bound=Command)
CommandHandler = Callable[[C, ...], None]
But this syntax is not possible.
I've found in the documentation that Concatenate could receive ... at the end,
Concatenate is currently only valid when used as the first argument to a Callable. The last parameter to Concatenate must be a ParamSpec or ellipsis (...).
so it could be:
C= TypeVar("C", bound=Command)
CommandHandler = Callable[Concatenate[C, ...], None]
But this returns an error from Pylance:

One could say Callback Protocol could solve this like:
C= TypeVar("C", bound=Command)
class CommandHandler(Protocol):
def __call__(self, __command: C, *__args: Any) -> None: ...
But it only receives functions that has an implicit variadic argument, it doesn't work with variadic forms of the function.
So far the only way I could solve this is through the Union of many Callables, but it doesn't look like the best solution.
At the end CommandHandler can only be defined as:
C= TypeVar("C", bound=Command)
CommandHandler = Union[
Callable[[C, Any], None],
Callable[[C, Any, Any], None],
Callable[[C, Any, Any, Any], None],
Callable[[C, Any, Any, Any, Any], None],
Callable[[C, Any, Any, Any, Any, Any], None],
Callable[[C, Any, Any, Any, Any, Any, Any], None],
Callable[[C, Any, Any, Any, Any, Any, Any, Any], None],
Callable[
[C, Any, Any, Any, Any, Any, Any, Any, Any], None
],
]
Related:
https://github.com/python/cpython/issues/88954
https://stackoverflow.com/questions/57658879/python-type-hint-for-callable-with-variable-number-of-str-same-type-arguments
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 issue 中描述的 Callable 和 Concatenate 文档开始,然后查看相关的 issue 88954 以及链接的 Stack Overflow 讨论。将所请求的 CommandHandler 形式与当前的 typing 规则进行比较,并确定受支持的设计是否能够表达这些形式;完成内容应包括一份达成一致的规范以及相应的文档或实现计划。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- tooling
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 30/100