简体   繁体   English

Python:在包模块中从主文件导入变量

[英]Python: import variable from main file at package module

i try to use a complex structure in flask restfull, my structure is the following: 我尝试在烧瓶restfull中使用复杂的结构,我的结构如下:

main.py
-models
-- __init__.py
--modelA.py
-resources
--__init__.py
--resourceA.py

I have a variable in main.py and i need this variable in models.modelA and i need also models.modelA in resources.resourceA. 我在main.py中有一个变量,我在models.modelA中需要此变量,在资源.resourceA中也需要model.modelA。 At this point everything is ok. 至此一切正常。 When i start my app, i get the following error: 当我启动我的应用程序时,出现以下错误:

Traceback (most recent call last):
  File "main.py", line 12, in <module>
    from resources.resourceA import functionA
  File "/var/www/project/resources/resourceA.py", line 11, in <module>
    from models.modelA import *
  File "/var/www/project/models/modelA.py", line 8, in <module>
    from main import mainvariable
  File "/var/www/project/main.py", line 12, in <module>
    from resources.resourceA import functionA
ImportError: cannot import name functionA

I hope your help 希望您的帮助

What you basically have here is called a circular import. 您在这里基本拥有的就是循环导入。 As the traceback states, your main module is importing functionA from resources.resourceA . 作为回溯状态,您的main模块是从resources.resourceA导入functionA And resourceA is importing models.modelA which is in turn trying to import main which again requires resources.resourceA . 并且resourceA正在导入models.modelA ,而该模型又试图导入main ,这再次需要resources.resourceA

Unless a particular order is resolved, python interpreter cannot understand how to resolve the modules. 除非解决了特定的顺序,否则python解释器无法理解如何解析模块。 You can however solve this problem in an easier way. 但是,您可以以更简单的方式解决此问题。

If the models.modelA doesn't require a module level import for main , you can shift the import to the function / class scope where you need its imports. 如果models.modelA不需要main的模块级导入,则可以将导入转移到需要导入的函数/类范围。

See here for more on circular imports . 有关循环进口的更多信息,请参见此处。

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

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