gpt4 book ai didi

python - 是否有 List 的协变可变版本?

转载 作者:行者123 更新时间:2023-12-04 09:31:49 25 4
gpt4 key购买 nike

我已经将我真正想要注释的代码归结为这个最小版本:

def print_it(numbers_or_nones):
for i, number in enumerate(numbers_or_nones):
if number is None:
numbers_or_nones[i] = 0
print("NOOOO")
else:
print(number)


numbers = [1, 2, 3, 4]
print_it(numbers)
我要注释参数 numbers_or_nonesprint_it .它必须是...
  • ... 元素为 Optional[int] 的泛型类型
  • ... 可迭代
  • ...支持索引分配

  • 这个案例的正确类型是什么? 请注意,无法更改 numbers : List[int] 的类型.我能看到的唯一选择是使用 typing.overload .
    列表
    最简单的就是 List[Optional[int]] .但是,这给出了:
    error: Argument 1 to "print_it" has incompatible type "List[int]"; expected "List[Optional[int]]"
    note: "List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance
    note: Consider using "Sequence" instead, which is covariant
    序列
    Unsupported target for indexed assignment ("Sequence[Optional[int]]")
    可变序列
    error: Argument 1 to "print_it" has incompatible type "List[int]"; expected "MutableSequence[Optional[int]]"

    最佳答案

    简短回答:没有协变可变集合,此处列出了处理这种情况的可能策略 https://mypy.readthedocs.io/en/stable/common_issues.html#invariance-vs-covariance

    为什么可变集合不能是协变的?
    因为这会导致严重的问题,例如:

    def make_first_None(numbers_or_nones: MutableSequence[Optional[int]]):
    numbers_or_nones[0] = None


    numbers: List[int] = [1, 2, 3, 4]
    make_first_None(numbers) # Error!! Numbers is not a List[int] anymore!!!
    关于为什么可变集合必须保持不变的详细解释在这里 https://mypy.readthedocs.io/en/stable/generics.html#variance-of-generics

    对于这种情况,文档中列出的三种策略如下所示:
  • 使用显式类型注释:

  • numbers: List[Optional[int]] = [1, 2, 3, 4]
    print_it(numbers)
  • 复制并传递
  • print_it(list(numbers))
  • 使用不可变集合

  • def print_it(numbers_or_nones: Sequence[Optional[int]]) -> List[int]:
    for number in numbers:
    if number is None:
    print("NOOOO")
    else:
    print(number)
    return [number or 0 for number in numbers]


    numbers = [1, 2, 3, 4]
    print_it(numbers)

    关于python - 是否有 List 的协变可变版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62814180/

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