我在模块attach_connection_pinging
中有一个函数mylib.tools.db
。我需要在mylib/__init__.py
中调用它:
from .tools import db
db.attach_connection_pinging()
或
from .tools.db import attach_connection_pinging
attach_connection_pinging()
但我不喜欢这个解决方案,因为它会在mylib
模块中创建不需要的名称。
我目前的解决方案是自动导入tools
包所需的子模块。 mylib/tools/__init__.py
:
from . import db
from . import log
然后在mylib/__init__.py
:
from . import tools
tools.db.attach_connection_pinging()
tools.db.make_psycopg2_use_ujson()
tools.log.attach_colorsql_logging()
嗯,这是我发现的最好的解决方法,但它并不理想。
理想情况下,这样的东西会更好,但显然不是在编译:
from . import tools.db
from . import tools.log
tools.db.attach_connection_pinging()
tools.db.make_psycopg2_use_ujson()
tools.log.attach_colorsql_logging()
有更好的解决方案吗?我错过了什么吗?
答案 0 :(得分:0)
你可以这样做:
from .tools import db as tools_db
from .tools import log as tools_log
或者,您的上一个示例将起作用:
import tools.db
唯一的问题是,如果你的python路径中有一些其他模块命名的工具,它将是不明确的。
最后,您可以选择修改当前的解决方法。在tools/__init__.py
:
__all__ = ["db", "log"]
然后:
from tools import *
tools.db
有一个问题是“db”也会存在于你的命名空间中,并与其他任何名为“db”的东西冲突。所以我建议第一个“导入为”解决方案。