python / python/typing

Does `field_specifier` support non-keyword arguments?

未关闭
#2,170 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic: documentation
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
8

描述

I was reading through the specification of dataclass_transform and it doesn't really specify what field_specifiers looks like. It mostly just says:

field_specifiers (tuple[Callable[..., Any], ...]) – Specifies a static list of supported classes or functions that describe fields, similar to dataclasses.field(). Defaults to ().

But dataclasses.field takes keyword-only arguments, which leaves it a bit ambiguous about whether positional arguments are ok. For example:

from typing import dataclass_transform, Any

def custom_field(default: object, *, init: bool = True) -> Any: ...

@dataclass_transform(field_specifiers=(custom_field,))
def build(x): ...

@build
class A:
    x: int = custom_field(default=0)

@build
class B:
    x: int = custom_field(0)

A()
B()

pyrefly, pyright, and mypy all flag B() as an error while ty accepts it without complaint.

My (uninformed) take is that this should be allowed -- custom_field(default=0) and custom_field(0) have the same runtime effect, so it feels like they should have the same type-checking effect too. This also matches how pydantic and attrs works (e.g. you can do pydantic.Field(1) and attr.ib(0)) -- today I suspect the type-checkers are special-casing this to make pydantic and attrs (since I've definitely used both without running into static type-checking errors about missing default values before).

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 dataclass_transform 规范及其 field_specifiers 定义入手;比较 pyrefly、pyright、mypy 和 ty 中的位置参数与关键字参数示例。确定是否应允许位置参数,然后在 typing specification 中记录这一决定;如果项目有相应示例或一致性测试,则添加一个。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
documentation
Issue 类型
文档
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

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