Python 模块和 __all__ [英] Python module and __all__

查看:25
本文介绍了Python 模块和 __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 模块导入 sessionengine 实例,例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆