python - Import nested submodules -
python - Import nested submodules -
i have function attach_connection_pinging
in module mylib.tools.db
. need phone call in mylib/__init__.py
:
from .tools import db db.attach_connection_pinging()
or
from .tools.db import attach_connection_pinging attach_connection_pinging()
but don't solution, because creates unneeded names in mylib
module.
my current solution auto-import needed submodules of tools
package. mylib/tools/__init__.py
:
from . import db . import log
then in mylib/__init__.py
:
from . import tools tools.db.attach_connection_pinging() tools.db.make_psycopg2_use_ujson() tools.log.attach_colorsql_logging()
well it's best workaround i've found, it's not ideal.
ideally nicer, not compiling:
from . import tools.db . import tools.log tools.db.attach_connection_pinging() tools.db.make_psycopg2_use_ujson() tools.log.attach_colorsql_logging()
is there improve solution? missing anything?
you do:
from .tools import db tools_db .tools import log tools_log
alternatively, lastly illustration work as:
import tools.db
the grab there if have other module named tools in python path, ambiguous.
lastly, take modify current workaround. in tools/__init__.py
:
__all__ = ["db", "log"]
then:
from tools import * tools.db
the grab there "db" exist in namespace , conflict else that's called "db". recommend first "import as" solution.
python
Comments
Post a Comment