Python导入突然停止工作

问题描述:

在我目前的项目中,我有以下结构:Python导入突然停止工作

- start.py (this script is run and imports from parentPackage and it's children) 
- parentPackage 
    - subPackage1 
    - __init__.py 
    - foo.py 
    - bar.py 
    - ... 
    - subPackage2 
    - __init__.py 
    - foo1.py 
    - bar2 
    - ... 
    - __init__.py 
    - someDataSource.py 
    - someOtherThing.py 
    - hereIsAnotherOne.py 
    - andSomeMore.py 

__init__.py文件(下划线不显示在SO)我说这样的进口:

例(parentPackage)

from .someDataSource.py import SomeDataSource 
from .someOtherThing.py import SomeOtherThing 
from .hereIsAnotherOne.py import HereIsAnotherOne 
from .andSomeMore.py import AndSomeMore 

我重复了这个子程序包的过程。

然后,当我想从.hereIsAnotherOne.py导入SomeDataSource我只是写:

from parentPackage import SomeDataSource 

这完美工作了几个星期,但现在突然停止工作。

我尝试从子包中删除__init__.py文件,并在parentPackage的__init__.py中执行那些导入,但这不起作用。

这怎么可能?我没有碰过__init__.py文件或任何东西,我只向parentPackage添加了一个新文件。

我在这里做错了什么?这一直对我有效。我意识到在这个问题上有很多答案,但似乎没有解决我的问题。

note:我使用PyCharm作为我的IDE,奇怪的是PyCharm认识到导入有效,没有任何警告,直到运行时。

谢谢大家!

PS:我运行python3.6

+0

强烈建议在Python中使用绝对导入:'from parent_package.sub_package.module import some_function'。请检查Python的风格PEP-8。 – tuned

你有一个圆形的进口:

parentPackage,你hereIsAnotherOnehereIsAnotherOne导入,您从parentPackage进口。您必须通过从源模块someDataSource.py直接导入SomeDataSource或在您使用它的功能内部本地导入它来解决该问题。

无论采用哪种方式,循环导入的发生都应该让您长时间思考重构当前的包体系结构。

+0

你好!那么从'.someDataSource.py import SomeDataSource'应该可以正常工作?可悲的是,事实并非如此。可能这些进口不是相对的吗? –