Python模块和__all__ [英] Python module and __all__
问题描述
我试图了解如何使用__all
管理模块.例如,我有以下结构化代码:
I trying to understand how to manage module with __all
. For example, I have following structured code:
main.py
|=> /database
|=> __init__.py
|=> engine (with variables engine, session, etc.)
现在,我希望能够直接从database
模块导入session
和engine
实例,例如:
now I want to be able to import session
and engine
instances directly from database
module like:
from database import session
我尝试将__all__ = ['session']
或__all__ = ['engine.session']
行添加到__init__py
,但是当我尝试导入时,出现了AttributeError: 'modile' object has not attribute 'engine.session'
异常.
I tried to add line __all__ = ['session']
or __all__ = ['engine.session']
to __init__py
but when I trying to do import I've got an exception AttributeError: 'modile' object has not attribute 'engine.session'
.
有什么方法可以实现想要的行为?
Is there any way to achieve wanted behavior?
推荐答案
在__all__
中列出名称本身不会将项目导入模块.如果您使用from database import *
语法,它所做的就是列出要从该模块导入的列表名称.
Listing names in __all__
does not, by itself, import items into a module. All it does is list names to import from that module if you used from database import *
syntax.
将session
导入database/__init__.py
:
from .engine import session
这篇关于Python模块和__all__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!