首页 > 解决方案 > What is the difference between "import package" versus "from package import ..."?

问题描述

Why are some packages such as Pandas always imported as:

import <name of package> #e.g. import pandas as pd

While other packages are "imported" as:

from <name of package> import <module> #e.g. from fredapi import Fred

I understand that when you want to import packages that have a lot of modules, you can import a specific module you need with

from <name of package> import <module> #e.g. from fredapi import Fred

versus importing the entire package and all it's modules.

My question is more about the packages that are only able to imported with:

from <name of package> import <module> #e.g. from fredapi import Fred

Is it because of the structure of the package? Is it because it's not actually a package? I'm confusing myself at this point. Hope someone could shed some light on this.

A concrete example, I can never import fredapi like this:

import fredapi

I can only use fredapi with the "from" command.

from fredapi import Fred

标签: pythonimportpackage

解决方案


将包想象成一个书架,其中包含一些您想阅读的书籍。

您可以选择一次阅读所有内容:

import bookshelf
# read bookshelf.book1, bookshelf.book2, until bookshelf.bookN

或者你可以一次挑几本书来读,

from bookshelf import book1, book5, bookN

在这两种情况下要注意的是,无论您如何阅读书籍,整个书架仍然占据您的书房空间。在 Python 世界中,这意味着无论是导入整个包,还是仅将选择的几个模块导入命名空间,都必须导入整个模块并将其保存在内存中。


推荐阅读