小编zat*_*heo的帖子

以哨兵值作为默认值的类型提示参数

目前,当我无法在函数签名中分配默认参数和/或已经具有含义时,我会使用此策略。None

from typing import Optional

DEFAULT = object()


# `None` already has meaning.
def spam(ham: Optional[list[str]] = DEFAULT):
    if ham is DEFAULT:
        ham = ['prosciutto', 'jamon']
    if ham is None:
        print('Eggs?')
    else:
        print(str(len(ham)) + ' ham(s).')
Run Code Online (Sandbox Code Playgroud)

错误:

Failed (exit code: 1) (2607 ms)

main.py:7: error: Incompatible default for argument "ham" (default has type "object", argument has type "Optional[List[str]]")
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)
  • 如何在 mypy 中输入提示ham而不出现错误?或者
  • 我应该使用什么策略来代替DEFAULT = object() …

python type-hinting mypy python-typing python-3.9

10
推荐指数
2
解决办法
1478
查看次数

与 Union 元素不兼容的类型

我最近收到了这个很好的答案,用于以下方面:

from typing import Union, cast


class Default:
    """Placeholder for default arguments."""


# ham[] is mutable.  `None` has meaning (or is not preferred).
def spam(ham: Union[list[str], None, type[Default]] = Default):
    if ham is Default:
        ham = ['prosciutto', 'jamon']
    #ham = cast(Union[list[str], None], ham)
    #assert isinstance(ham, (list, type(None)))
    if ham is None:
        print('Eggs?')
    else:
        print(str(len(ham)) + ' ham(s).')
Run Code Online (Sandbox Code Playgroud)

mypy错误:

Failed (exit code: 1) (2655 ms)

main.py:17: error: Argument 1 to "len" has incompatible type "Union[List[str], Type[Default]]"; expected "Sized" …
Run Code Online (Sandbox Code Playgroud)

python type-hinting mypy python-typing python-3.9

1
推荐指数
1
解决办法
909
查看次数

标签 统计

mypy ×2

python ×2

python-3.9 ×2

python-typing ×2

type-hinting ×2