Python 命名空间“导入 X"和“从 X 导入"

2022-01-14 00:00:00 python python-3.x sqlalchemy namespaces

问题描述

以下代码有效:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

但是,以下内容:

import sqlalchemy
Base = sqlalchemy.ext.declarative.declarative_base()

抛出:模块sqlalchemy"没有属性ext".怎么可能?


解决方案

sqlalchemy 是一个包,导入一个包并不会自动加载它的子模块.当你这样做时

sqlalchemy is a package, and importing a package doesn't automatically load its submodules. When you do

import sqlalchemy
Base = sqlalchemy.ext.declarative.declarative_base()

导入系统不会加载 sqlalchemy.ext 子模块,因为您没有要求它.

The import system doesn't load the sqlalchemy.ext submodule, because you didn't ask for it.

当你这样做时

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

您已明确要求加载 sqlalchemy.extsqlalchemy.ext.declarative,因此访问有效.

You've explicitly requested that sqlalchemy.ext and sqlalchemy.ext.declarative get loaded, so the access works.

你也可以这样做

import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()

这也将加载 sqlalchemy.extsqlalchemy.ext.declarative.

有些包会在 __init__.py 中自动加载其子模块,因此您不必显式导入子模块.不过,这不是您应该依赖的东西.

Some packages automatically load their submodules inside their __init__.py, so you don't have to import submodules explicitly. This isn't something you should rely on, though.

相关文章