gpt4 book ai didi

python - Mypy 提示默认参数值与省略号不兼容

转载 作者:行者123 更新时间:2023-12-05 06:06:46 24 4
gpt4 key购买 nike

我试图找到一种方法来区分参数是否已传递给方法。例如,我有以下功能:

@dataclass
class Record:
id: int
name: str
completed_at: Optional[date] = None


records = [
Record(id=1, name="Foo", completed_at=date(2021, 1, 10)),
Record(id=2, name="Bar", completed_at=date(2021, 1, 11)),
]

def update_record(
id: int,
name: Optional[str] = None,
completed_at: Optional[date] = ..., # type: ignore
):
record = next(record for record in records if record.id == id)

if name is not None:
record.name = name

if completed_at is not ...:
record.completed_at = completed_at

它就像一个魅力,但当我删除 # type: ignore 评论时,mypy 提示以下错误:

error: Incompatible default for argument
"completed_at" (default has type "ellipsis", argument has type
"Optional[date]") [assignment]
... int, name: Optional[str] = None, completed_at: Optional[date] = ...

我已经尝试过使用虚拟“哨兵”对象的解决方案,例如:

DO_NOTHING = object()

def update_record(id, completed_at: Union[DO_NOTHING, None, date] = DO_NOTHING):
pass

...但在我看来它有点过于冗长。

有没有办法以更简洁的方式做得更好?

最佳答案

似乎 @overload 来自 typing 模块完全符合我的要求。完整示例:

@dataclass
class Record:
id: int
name: str
completed_at: Optional[date] = None


records = [
Record(id=1, name="Foo", completed_at=date(2021, 1, 10)),
Record(id=2, name="Bar", completed_at=date(2021, 1, 11)),
]


@overload
def update_record(id: int):
...


@overload
def update_record(
id: int, name: Optional[str] = None, completed_at: Optional[date] = None
):
...


def update_record(id: int, *args, **kwargs):
record = next(record for record in records if record.id == id)

for field, value in kwargs.items():
setattr(record, field, value)


def test_update():
repository = Repository(records)
repository.update(1, name="Foobar") # Do nothing with `completed_at` field
repository.update(2, completed_at=None) # Set `completed_at` to None
# repository.update(2, completed_at="2021-01-12") # Typing error

assert records == [
Record(id=1, name="Foobar", completed_at=date(2021, 1, 10)),
Record(id=2, name="Bar"),
]

我希望有人会觉得它有用。

关于python - Mypy 提示默认参数值与省略号不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65666958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com