相关疑难解决方法(0)

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

目前,当我无法在函数签名中分配默认参数和/或已经具有含义时,我会使用此策略。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
查看次数

标签 统计

mypy ×1

python ×1

python-3.9 ×1

python-typing ×1

type-hinting ×1