简体   繁体   English

如何使用标准库包名解析Python包中的命名空间冲突?

[英]How do I resolve namespace conflicts in my Python packages with standard library package names?

I am developing a package with the following structure on disk: 我正在开发一个在磁盘上具有以下结构的包:

foo/
   __init__.py
   xml.py
   bar.py
   moo.py

The xml.py package provides a class that does some custom XML parsing and translation for the other package components using a SAX stream parser. xml.py包提供了一个类,该类使用SAX流解析器为其他包组件执行一些自定义XML解析和转换。 So it has in it: 所以它有:

import xml.sax
import xml.sax.handler

But when I go to use foo.xml in an application I get: 但是当我在应用程序中使用foo.xml ,我得到:

Traceback (most recent call last):
  File "testxmlparser.py", line 15, in <module>
    import foo.xml
  File "~/code/foo/xml.py", line 39, in <module>
    import xml.sax
ImportError: No module named sax

I appear to have a namespace conflict. 我似乎有一个命名空间冲突。 If I rename xml.py to something else like xmlparser.py everything works as expected. 如果我将xml.py重命名为xmlparser.py东西,一切都按预期工作。 But this feels like the wrong thing to do. 但这感觉是错误的做法。 I feel like I'm missing something fundamental about package names and resolution in Python here. 我觉得我在这里缺少Python中包名和解析的基本内容。

Is there a proper way to make this work that doesn't involve me renaming the foo/xml.py file? 有没有一种正确的方法来完成这项工作,而不涉及我重命名foo/xml.py文件? Or is that really the only solution to the conflicting names? 或者这真的是冲突名称的唯一解决方案吗?

Edit: The "avoid naming things the same as standard Python modules" seems...well..a mineshaft to me. 编辑:“避免命名与标准Python模块相同的东西”似乎......好吧..给我一个mineshaft。 That's a moving target, the standard module set, that's bound to change and grow over time. 这是一个移动目标,标准模块集,随着时间的推移必然会发生变化和增长。 So unless you get really creative with your names the rename-things-until-you-find-something-that-doesn't-conflict solutions seems poor to me. 因此,除非你真正对自己的名字有所了解,否则重命名 - 事物 - 直到找到 - 某些不冲突的解决方案对我来说似乎很不好。 Besides, I've got it in a unique package name with foo already (I'm not using foo , but something that is definitely unique), shouldn't that be enough? 此外,我已经用foo的独特包装名称(我不是使用foo ,但绝对是独一无二的),这应该不够吗?

As mentioned over here , use 如前所述在这里 ,使用

from __future__ import absolute_import

and use relative imports if needed. 并在需要时使用相对导入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM