简体   繁体   English

Python名称空间“ import X”和“ from X import”

[英]Python namespace 'import X' and 'from X import'

The following code works: 以下代码有效:

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

However, the following: 但是,以下内容:

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

throws: module 'sqlalchemy' has no attribute 'ext' . 抛出: module 'sqlalchemy' has no attribute 'ext' How can that be? 怎么可能?

sqlalchemy is a package, and importing a package doesn't automatically load its submodules. sqlalchemy是一个程序包,导入程序包不会自动加载其子模块。 When you do 当你做

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

The import system doesn't load the sqlalchemy.ext submodule, because you didn't ask for it. 导入系统不会加载sqlalchemy.ext子模块,因为您没有要求它。

When you do 当你做

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

You've explicitly requested that sqlalchemy.ext and sqlalchemy.ext.declarative get loaded, so the access works. 您已明确要求加载sqlalchemy.extsqlalchemy.ext.declarative ,因此访问有效。

You also could have done 你也可以做

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

which would also load sqlalchemy.ext and sqlalchemy.ext.declarative . 这也将加载sqlalchemy.extsqlalchemy.ext.declarative

Some packages automatically load their submodules inside their __init__.py , so you don't have to import submodules explicitly. 一些软件包会自动在__init__.py加载其子模块,因此您不必显式导入子模块。 This isn't something you should rely on, though. 但是,这不是您应该依靠的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM