簡體   English   中英

Mypy 無法從文字列表中推斷項目的類型

[英]Mypy can't infer the type of items from a list of Literals

我有一個變量x和一個文字列表(比如 0、1、2)。 我想將x轉換為這些文字之一:如果x在列表中,我將其返回; 否則我返回一個后備值:

from typing import Literal, Set

Foo = Literal[0, 1, 2]
foos: Set[Foo] = {0, 1, 2}
 
def convert_to_foo(x: int) -> Foo:
  if x in foos:
    # x must have type Foo, yet this doesn't type check
    y: Foo = x
    return y
  return 0

不幸的是,這不會進行類型檢查。 Mypy 返回以下消息(請參閱gist ):

main.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "Union[Literal[0], Literal[1], Literal[2]]")

如果我屬於Foo的列表,那么我就是Foo ,對嗎? 我在文檔中找不到答案,有人可以指出我正確的方向嗎?

很好的問題。 認為cast可能是 go 的唯一途徑:

from typing import Literal, Set, cast

Foo = Literal[0, 1, 2]
foos: Set[Foo] = {0, 1, 2}
 
def convert_to_foo(x: int) -> Foo:
    if x in foos:
        y: Foo = cast(Foo, x)
        return y
    return 0

我已經在 windows Python3.8 上測試了你的代碼,沒有發現任何問題。

from typing import Literal, Set

Foo = Literal[0, 1, 2]
foos: Set[Foo] = {0, 1, 2}

def convert_to_foo(x: int) -> Foo:
    if x in foos:
        # x must have type Foo, yet this doesn't type check
        y: Foo = x
        print(y)
        return y
    return 0

>>> convert_to_foo(3)
0
>>> convert_to_foo(2)
2
2

你到底想做什么? 在這里,它檢查是否為 3,如果 2 返回 2,則返回 0。這不是您檢查的內容嗎?

我試過這個x:Any, default: int

from typing import Literal, Set
from typing import *

Foo = Literal[0, 1, 2]
foos: Set[Foo] = {0, 1, 2}

def convert_to_foo(x:Any, default: int) -> Foo:
  if x in foos:
    # x must have type Foo, yet this doesn't type check
    y: Foo = x
    return y
  return 0

成功:在 1 個源文件中未發現問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM