[英]Module 'a' has no attribute 'b' while importing module from same directory
我的Python项目中具有以下目录结构:
- dump_specs.py
/impa
- __init__.py
- server.py
- tasks.py
我对循环引用有疑问。 dump_specs.py
需要从server.py
对app
的引用。 server.py
是Flask应用程序,需要引用tasks.py
celery任务。 所以dump_specs.py
看起来像:
#!/usr/bin/env python3
import impa.server
def dump_to_dir(dir_path):
# Do something
client = impa.server.app.test_client()
# Do the rest of things
impa/server.py
看起来像:
#!/usr/bin/env python3
import impa.tasks
app = Flask(__name__)
# Definitions of endpoints, some of them use celery tasks -
# that's why I need impa.tasks reference
和impa/tasks.py
:
#!/usr/bin/env python3
from celery import Celery
import impa.server
def make_celery(app):
celery = Celery(app.import_name,
broker=app.config['CELERY_BROKER_URL'],
backend=app.config['CELERY_RESULT_BACKEND'])
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
return celery
celery = make_celery(impa.server.app)
当我尝试使用./dump_specs.py
转储规范时,出现错误:
./dump_specs.py specs
Traceback (most recent call last):
File "./dump_specs.py", line 9, in <module>
import impa.server
File "/build/impa/server.py", line 23, in <module>
import impa.tasks
File "/build/impa/tasks.py", line 81, in <module>
celery = make_celery(impa.server.app)
AttributeError: module 'impa' has no attribute 'server'
而且我不明白怎么了。 有人可以解释发生了什么以及如何消除此错误吗?
如果我设法在主机上正确重现您的问题,它应该可以帮助您将import impa.tasks
插入到dump_specs.py
上方的 import impa.server
。
模块之间相互依赖的方式,加载顺序很重要。 IIRC(文档中对加载机制进行了更详细的描述),当您首次尝试导入impa.server
,它将在第23行尝试导入impa.tasks
,但是impa.server
导入尚未完成。 有import impa.server
在impa.tasks
,但我们不回来,此时导入(我们会另有一整圈结束),并继续导入impa.tasts
直到我们想访问impa.server.app
,但是我们还没有做到这一点, impa.server
尚未导入。
如果可能的话,如果未在导入时执行访问包中另一个模块的代码,也将有所帮助(直接作为模块的一部分调用,而不是在导入完成后将被调用/使用的函数或类中) )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.