簡體   English   中英

即使我檢查無,為什么 mypy 標記“項目無沒有屬性 x”錯誤?

[英]Why does mypy flag "Item None has no attribute x" error even if I check for None?

嘗試使用類型提示執行 Python (3.8.8) 並從 mypy (0.931) 獲取我無法理解的錯誤。

import xml.etree.ElementTree as ET
tree = ET.parse('plant_catalog.xml')  # read in file and parse as XML
root = tree.getroot()  # get root node
for plant in root:  # loop through children
    if plant.find("LIGHT") and plant.find("LIGHT").text == "sun" 
        print("foo")

這會引發 mypy 錯誤Item "None" of "Optional[Element]" has no attribute "text" 但為什么? 我確實在 if 子句的前半部分檢查了plant.find("LIGHT")返回None的可能性。 如果第一部分失敗,則訪問.text屬性的第二部分甚至不會執行。

如果我修改為

    lights = plant.find("LIGHT")
    if lights:
        if lights.text == selection:            
            print("foo")

錯誤消失了。

那么這是因為plant object 可能仍會在第一次檢查和第二次檢查之間發生變化嗎? 但是分配給變量並不會自動復制內容,它仍然只是對可能更改的 object 的引用。 那么為什么會第二次通過呢?

(是的,我知道重復.find()兩次也不省時。)

mypy不知道plant.find("LIGHT")總是返回相同的值,因此它不知道您的測試是適當的保護。

所以你需要將它分配給一個變量。 就 mypy 而言,該變量不能在不重新分配的情況下從一個 object 更改為另一個,並且如果您不對它執行一些其他操作,它的內容也不會改變。

暫無
暫無

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

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