简体   繁体   English

具有相同名称的 Python 模块和包

[英]Python module and package having the same name

Below is an example of my project.下面是我的项目的一个例子。

When running foo.py I get:运行foo.py 时,我得到:

ModuleNotFoundError: No module named 'foo.bar'; ModuleNotFoundError: 没有名为“foo.bar”的模块; 'foo' is not a package 'foo' 不是一个包

Renaming the foo/ directory or the foo.py file solves the problem, but I'd love to know if there is another way and why this is happening?重命名foo/目录或foo.py文件可以解决问题,但我很想知道是否有其他方法以及为什么会发生这种情况?

project/
        |
        foo/
        |  __init__.py
        |  foo.py
        |  bar.py
        |
        setup.py

In foo.py在 foo.py

import foo.bar

    if __name__=='__main__':
       pass

The issue is likely how you're running foo.py as a script.问题可能是您如何将foo.py作为脚本运行。 If you run python foo.py from inside the project/foo directory, Python will assume that foo.py is a module at the global level, and that will prevent the foo/ folder from being seen as a global package (even if project/ is in the module search path).如果您从project/foo目录中运行python foo.py ,Python 将假定foo.py是全局级别的模块,这将防止foo/文件夹被视为全局包(即使project/位于模块搜索路径中)。 It would expect to import bar.py as bar at the top level too, rather than as a module within a foo package.它也希望将bar.py作为bar在顶层导入,而不是作为foo包中的模块。

You can probably work around this issue by changing how you run foo.py .您可能可以通过更改运行foo.py解决此问题。 Instead of python foo.py , try python -m foo.foo (from the project/ folder, if necessary).而不是python foo.py ,尝试python -m foo.foo (从project/文件夹,如有必要)。

It may also be possible to work around some of the issues by setting a __package__ value in your modules (see here for another answer explaining __package__ and providing some useful links).也可以通过在模块中设置__package__值来解决一些问题(请参阅此处了解解释__package__并提供一些有用链接的另一个答案)。 That might only fix explicit relative imports between modules in the package though (so you could change import foo.bar to from . import bar and it would work), but I'm not sure if it can restore the foo package to its proper place in the global namespace (so other code outside the package might still break).这可能只会修复包中模块之间的显式相对导入(因此您可以将import foo.bar更改为from . import bar并且它会起作用),但我不确定它是否可以将foo包恢复到其正确的位置在全局命名空间中(因此包外的其他代码可能仍会中断)。

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

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