[xml.dom.minidom] nodeValue attr is not defined on Node class but directly on all derived classes

未關閉
#100,710 0 則留言 1 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

評估

難度
1/5
預估耗時
1 小時以內
新手友好度
25/100
Issue 類型
缺陷
描述清晰度
描述清楚
活躍度
停滯
技術堆疊
python
領域
backend

研究方向

從 Lib/xml/dom/minidom.py 中 issue 連結的 Node 定義開始,將其屬性與衍生節點類別中定義的屬性進行比較。當 Node 依照文件一致地公開 nodeValue,且靜態分析器可以透過 Node 參照存取它時,修改即完成;檢查其他有文件說明的 Node 屬性是否也存在相同的遺漏。

由索引模型根據 Issue 內容生成。

描述

topic-typing topic-XML type-bug

[xml.dom.minidom] nodeValue attr is not defined on Node class but directly on all derived classes

According to the documentation, the Node class is supposed to have an attribute nodeValue that "has a different meaning for each node type; see the DOM specification for details.. [...] The value is a string or None."". However, this attribute is undefined on the Node class, but is then implemented on all derived classes (DocumentFragment, Attr, Element, ProcessingInstruction, CharacterData, DocumentType, Entity, Notation, Document).

As a result, IDEs and static analysers raise false positives when analysing "correct" code.

from xml.dom import minidom

dummy_xml: str = """<?xml version="1.0"?>
<Envelope>
  <Body>
    <StockName>T</StockName>
    <StockName>N</StockName>
  </Body>
</Envelope>
"""

dom: minidom.Document = minidom.parseString(dummy_xml)
body: minidom.Element = dom.getElementsByTagName("Body")[0]

child_node: minidom.Node
for child_node in body.childNodes:
  inner_node: minidom.Node | None = child_node.firstChild
  if inner_node is not None:
    	print(inner_node.nodeValue)

The example above prints T and N as expected, but Pylance reports the following issue:

Cannot access member "nodeValue" for type "Node"
Member "nodeValue" is unknown - Pylance (reportGeneralTypeIssues)

Indeed the nodes we process happen to be Elements - therefore the attribute is defined at runtime. However during static analysis this is unknown despite this being legal according to the documentation.

Proposed solution

As far as i can tell this would be very easy to fix: just by initializing this attribute to None in the Node class (as is done for other similar attributes), this problem could be fully resolved:
https://github.com/python/cpython/blob/b99ac1dbc081e4f2d2e68906e9c7c535e628611a/Lib/xml/dom/minidom.py#L34-L40

While we're at it it'd be worth double checking if other attributes are affected by the same issue. I can submit a PR in a few hours if you'd like.

My environment

  • CPython versions tested on: 3.8.2, 3.10.8, 3.11.0
  • Operating system and architecture: RHEL7.9 x86_64, Windows 10 x86_64
Linked PRs
  • gh-155586
主要語言
Python
星號
77.2k
分支
36k
平均合併
1 天 9 小時
30 天內合併 PR
558

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

python/cpython 的其他 Issue

查看 python/cpython 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。