etree: Defining the default namespace prefix (`""`) with register_namespace has issues
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 36k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
Granted the register_namespace() functionality should be used for 'well known namespace prefixes' but if the the default namespace prefix ("") is registered, the following issues can occur:
Duplicate default namespace attrs xmlns=''
import xml.etree.ElementTree as ET
ET.register_namespace("", "default")
e = ET.Element("{default}elem")
print(ET.tostring(e, default_namespace="otherdefault"))
# b'<elem xmlns="otherdefault" xmlns="default" />'
Incorrect serialisation (the noPrefixElem should raise an error but now it looks like it is in the default namespace):
import xml.etree.ElementTree as ET
ET.register_namespace("", "default")
e = ET.Element("{default}elem")
ET.SubElement(e, "noPrefixElem")
print(ET.tostring(e))
# b'<elem xmlns="default"><noPrefixElem /></elem>'
The two approaches to address this that I can think of are:
- Raise an error if the default namespace is passed to
register_namespace()- Lucky users that register
""but don't use the default prefix's URI anywhere or has every element qualified will have working code with no issues. This would cause their working code to break.
- Lucky users that register
- Handle it properly in
ElementTree._namespaces()by setting the default_namespace var in that function from the global registry if thedefault_namespaceargument isNone- Existing code that 'works' may raise errors about
ValueError: cannot use non-qualified names with default_namespace option, but at least erroneous xml would no longer be emitted - It may be possible to make it so code that was luckily unaffected still doesn't raise an error
- May result in #61290
- Existing code that 'works' may raise errors about
I'm happy to give the second option a try (with implementing any changes required for #61290) as I've also been looking into #57587 that also needs to handle potentially multiple definitions of the default_namespace. My current thinking is that if default_namespace is provided to _namespaces(), it takes precedence even if the default namespace is also defined in the global registry.
CPython versions tested on:
3.12, CPython main branch
Operating systems tested on:
macOS
Linked PRs
- gh-118417
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
先从 xml.etree.ElementTree.register_namespace()、ElementTree._namespaces() 和 ET.tostring() 开始,然后复现 issue 中的两个示例。在选择默认命名空间的优先级之前,检查链接的 PR gh-118417 以及相关的命名空间行为。完成的标准是序列化不再发出重复声明,也不再默默地将未限定元素视为属于默认命名空间。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100