Arthur.V
Arthur.V

Reputation: 706

Importing a module under a module (pandas.io.data)

I've just encountered something that bothers me.
I always thought that importing a 'parent' module should import everything under it.
But, when running:

import pandas
pandas.io.data

I get an error: AttributeError: 'module' object has no attribute 'data'.

However running:

import pandas.io.data

Leads to no error and the module is imported.
Could someone please explain this behavior?

Upvotes: 0

Views: 1080

Answers (2)

msvalkon
msvalkon

Reputation: 12077

The reason for this is that pandas.io is a submodule of the pandas package. Subpackages or submodules are not imported automatically, although you can do this in the __init__.py of your module if you wish to (usually you don't want to do this).

Packaging in python is fairly simple. If a folder has an __init__.py file, it's treated as a package. In this file you can lay out any initialization routines for your package. The file can also be empty. If a subfolder in your package contains its own __init__.py, this folder is considered to be a subpackage.

If you look that the pandas folder structure you'll see that io is a subpackage. The main __init__.py does not import pandas.io.data which is why you have to do it yourself.

Upvotes: 2

Pavel Ryvintsev
Pavel Ryvintsev

Reputation: 1008

"import" does not import child modules. You can write:

from pandas import *

but it is not recommended, since it violates the principle "Explicit is better than implicit".

Upvotes: 0

Related Questions