gpt4 book ai didi

python - 如何注释 Optional[int] 的包装器?难度 : when it's a parameter

转载 作者:行者123 更新时间:2023-12-04 13:32:26 24 4
gpt4 key购买 nike

我似乎无法为接收以下值的变量找到可接受的注释:a) 函数返回 int或 b) None .问题在于函数返回的值是父函数的可选关键字参数,所以之前声明为Optional[int] .但是,运行时赋值保证函数永远不会返回 None .
如果我删除注释,mypy接受它为黄金。但我更喜欢使用一些(可接受的)注释。一分钱,一磅...
我的代码:

from typing import Optional, Callable


def myfun(p1: Optional[int] = None):
# mypy complains about this
dyn_p1:Optional[Callable[[], int]] = (lambda: p1) if p1 else None

# ... but has no problem with this
# dyn_p1 = (lambda: p1) if p1 else None

otherFun(dyn_p1)


# I expect the parameter annotation here to be checked at the point of invocation above.
def otherFun(dyn_p1: Optional[Callable[[], int]]):
pass
这是 mypy错误:
PS $ mypy .\prompt_toolkit\shortcuts\test1.py
prompt_toolkit\shortcuts\test1.py:6: error: Incompatible types in assignment (expression has type "Optional[Callable[[], Optional[int]]]", variable has type "Optional[Callable[[], int]]")
prompt_toolkit\shortcuts\test1.py:6: error: Incompatible return value type (got "Optional[int]", expected "int")
Found 2 errors in 1 file (checked 1 source file)

# comment out the first dyn_p1 and uncomment the second, run again:
PS $ mypy .\prompt_toolkit\shortcuts\test1.py
Success: no issues found in 1 source file

最佳答案

它只需要更改如下

from typing import Optional, Callable


def myfun(p1: Optional[int] = None):
dyn_p1: Optional[Callable[[], Optional[int]]] = (lambda: p1) if p1 else None
otherFun(dyn_p1)


def otherFun(dyn_p1: Optional[Callable[[], Optional[int]]]):
pass
这是因为您已经明确地将 p1 定义为一个可选的 int,因此如果 p1 要由 lambda 返回,那么 dyn_p1 必须能够返回一个可选的 int,而不仅仅是一个 int。
现在运行 mypy
(venv) ➜  pythonProject mypy okay.py
Success: no issues found in 1 source file

关于python - 如何注释 Optional[int] 的包装器?难度 : when it's a parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64203221/

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