[英]ImportError: cannot import name 'variable' from 'module'
I am using Flask for my web framework. 我将Flask用于我的Web框架。 I am having an issue with imports.
我的进口商品有问题。 I am not understanding why can't I import my variable when I declare it within my
my_app/__init__.py
: 我不明白为什么在
my_app/__init__.py
声明变量时为什么不能导入变量:
from flask import Flask
from flask_login import LoginManager
from my_app.some_module.my_class.py import auth
app = Flask(__name__)
login_manager = LoginManager()
class Config:
def __init__(self):
pass
config = Config()
My conflictuous imports are present in my_app/some_module/my_class.py
: 我的冲突导入出现在
my_app/some_module/my_class.py
:
from flask import Blueprint
from my_app import login_manager # this one works fine
from my_app import config
auth = Blueprint('auth', __name__)
I run the app with run.py
: 我使用
run.py
运行该应用程序:
from my_app import app
app.run(debug=True)
I then get the error: 然后我得到错误:
Traceback (most recent call last):
...
File ".../my_app/some_module/my_class.py", line 1, in <module>
from my_app import login_manager, config
ImportError: cannot import name 'config' from 'my_app' (.../my_app/__init__.py)
Project structure is: 项目结构为:
my_app
+ __init__.py
some_module
+ __init__.py
+ my_class.py
+ run.py
The problem is that you have a cyclic dependency. 问题是您具有循环依赖性。 By the time you import
auth
from my_app.some_module.my_class.py
your config
is not set yet. 到从
my_app.some_module.my_class.py
导入auth
,您的config
尚未设置。 Try moving that import to the end of the my_app/__init__.py
file like: 尝试将导入导入移动到
my_app/__init__.py
文件的末尾,如下所示:
from flask import Flask
from flask_login import LoginManager
app = Flask(__name__)
login_manager = LoginManager()
class Config:
pass
config = Config()
from my_app.some_module.my_class.py import auth
You have a cyclic import: my_app.some_module
-> my_app.some_module.my_class
-> my_app.some_module
. 您有一个循环导入:
my_app.some_module
> my_app.some_module.my_class
> my_app.some_module
。
You can fix this by moving both Config
and config
to a separate module my_app.some_module.config
. 您可以通过将
Config
和config
都移动到单独的模块my_app.some_module.config
来解决此my_app.some_module.config
。
# my_app.some_module.my_config
class Config:
pass
config = Config()
# my_app.some_module.my_class
from .my_config import config
# my_app.some_module.__init__
from .my_config import config
from .my_class import MyClass
This means that every import does not depend on previous imports: 这意味着每次导入都不依赖于先前的导入:
my_app.some_module
|-> my_app.some_module.my_class -> my_app.some_module.config
\-> my_app.some_module.my_config
Doing imports this way instead of moving the import for .my_class
to the end of __init__.py
is more robust. 以这种方式进行导入,而不是将
.my_class
的导入移动到__init__.py
的末尾,会更可靠。 You can freely reorder the imports of .my_class
and .my_config
at the top of files. 您可以在文件顶部随意重新排列
.my_class
和.my_config
的导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.