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

查看:98
本文介绍了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天全站免登陆