Mainnoob
Mainnoob

Reputation: 31

Why does "import PIL; PIL.Image" not work, but "from PIL import Image" does?

In a python interpreter:

>>> import PIL
>>> PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
>>> from PIL import Image
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.7/site-packages/PIL/Image.pyc'>

Why do I have to make the import as "from PIL import Image"? I'm interested in both "what is the underlying working in python imports that makes this behaviour possible?" and "Why was the PIL package designed to work like this?"

Also, I really like to keep a clean namespace when programming. If I want to use PIL.Image in my code, should I import like this:

>>> import PIL
>>> from PIL import Image
>>> del Image

or is there a better way?

Upvotes: 3

Views: 1521

Answers (2)

eugenhu
eugenhu

Reputation: 1238

PIL.Image is a submodule of PIL and so won't be automatically imported with,

import PIL

since Python doesn't recursively import submodules.

5.4.2. Submodules in the Python Language Reference may help to understand the behaviour of importing submodules.

When a submodule is loaded using any mechanism, ... a binding is placed in the parent module’s namespace to the submodule object.

So although after importing and loading a submodule,

import PIL
from PIL import Image

you are able to access it via PIL.Image, this does not mean PIL.Image is loaded when importing the PIL module.


Also, I couldn't find this explicitly stated anywhere but from what I've tested, it seems to be that when you import a submodule either like:

import package.submodule

or:

from package import submodule

The parent package is also loaded in the process.

Upvotes: 2

Alasdair
Alasdair

Reputation: 308909

You could import PIL.Image:

import PIL.Image
PIL.Image.open('my_pic.jpg')

I think that Pillow is structured this way because of the history of the package. The original package PIL allowed you to do import Image. Pillow, the fork of PIL which supports Python 3, moved Image to the PIL namespace. The suggested import from PIL import Image makes it easy to switch from PIL to Pillow. See the porting docs for more info.

Upvotes: 3

Related Questions