Python PIL has no attribute 'Image'

PythonImportPython Imaging-Library

Python Problem Overview


I'm using python2.6 and got a problem this morning. It said 'module' has no attribute 'Image'. Here is my input. Why the first time I can not use PIL.Image?

>>> 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
>>> Image
<module 'PIL.Image' from '/usr/lib/python2.6/dist-packages/PIL/Image.pyc'>
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.6/dist-packages/PIL/Image.pyc'>

Python Solutions


Solution 1 - Python

PIL's __init__.py is just an empty stub as is common. It won't magically import anything by itself.

When you do from PIL import Image it looks in the PIL package and finds the file Image.py and imports that. When you do PIL.Image you are actually doing an attribute lookup on the PIL module (which is just an empty stub unless you explicitly import stuff).

In fact, importing a module usually doesn't import submodules. os.path is a famous exception, since the os module is magic.

More info:
The Image Module

Solution 2 - Python

If you, like me, found the accepted answer a bit befuddling because you could swear you've been able to use

import PIL
PIL.Image

sometimes before, a potential reason for this is if any other code in your Python session has run from PIL import Image or import PIL.Image, even if it's in a completely different scope, you will be able to access PIL.Image.

In particular, matplotlib does so when it's imported. So if you run

import matplotlib
import PIL
PIL.Image

it works. Thanks, Python.

Don't trust anyone. Don't trust Python. Use import PIL.Image.

Solution 3 - Python

You can do:

try:
    import Image
except ImportError:
    from PIL import Image

it's better to use pillow instead PIL.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSquallView Question on Stackoverflow
Solution 1 - PythonAntimonyView Answer on Stackoverflow
Solution 2 - PythonconvoliutionView Answer on Stackoverflow
Solution 3 - PythonReza-S4View Answer on Stackoverflow