簡體   English   中英

輸入/mypy:dict[key] 和 dict.get(key) 之間的區別?

[英]typing/mypy: difference between dict[key] and dict.get(key)?

這是我的測試腳本:

class A:
    def __init__(self, config: dict) -> None:
        self.config = config


def test_func(a: int) -> None:
    pass


main_config = {"a": "x"}
a = A(config=main_config)

# value direct
test_func(1)  # line 14
test_func("b")  # line 15

# value with wrong type from dict
test_func(main_config["a"])  # line 18
test_func(main_config.get("a"))  # line 19

# value with wrong type from dict in class instance
test_func(a.config["a"])  # line 22
test_func(a.config.get("a"))  # line 23

如果我用 mypy (0.910) 測試它,我會得到以下結果:

> mypy test.py                                                                                                                                                                                                                                           
test.py:15: error: Argument 1 to "test_func" has incompatible type "str"; expected "int"
tests.py:18: error: Argument 1 to "test_func" has incompatible type "str"; expected "int"
tests.py:19: error: Argument 1 to "test_func" has incompatible type "Optional[str]"; expected "int"
tests.py:23: error: Argument 1 to "test_func" has incompatible type "Optional[Any]"; expected "int"
Found 4 errors in 1 file (checked 1 source file)


為什么 mypy 錯過/不報告第 22 行的呼叫?

只是一個假設:

dict.__getitem__() (又名a.config[...] )沒有類型注釋。 雖然dict.get有:

def get(self, key: _KT) -> Optional[_VT_co]: ...

我的假設的簡單證明:

from typing import Optional, Any


def test_func(a: int) -> None:
    pass

def foo(a):
    if a == 1:
        return 123
    elif a == 2:
        return 'asd'
    else:
        raise ValueError


def foo_typed(a) -> Optional[Any]:
    if a == 1:
        return 123
    elif a == 2:
        return 'asd'
    else:
        return None


test_func(foo(2))
test_func(foo_typed(2)) # line 26

只生產:

main.py:26: error: Argument 1 to "test_func" has incompatible type "Optional[Any]"; expected "int"

即使foo(2)返回str

暫無
暫無

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

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