Python PIL has no attribute 'Image'
Asked Answered
G

4

63

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'>
Guizot answered 11/8, 2012 at 2:46 Comment(0)
M
83

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

Mildredmildrid answered 11/8, 2012 at 2:59 Comment(0)
C
50

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.

Cassilda answered 9/9, 2021 at 23:39 Comment(2)
this answer is eye-opening and should be a part of the main answerDeandreadeane
This behavior is a core feature of the Python import system (docs.python.org/3/reference/import.html#the-module-cache ) which ensure that different parts of the process have the same view of what an imported module is. Without this it would be impossible to use module-level sentinels or to safely pass objects wrapping c-extensions between different parts of your program.Cauldron
P
9

You can do:

try:
    import Image
except ImportError:
    from PIL import Image

it's better to use pillow instead PIL.

Prole answered 11/7, 2014 at 6:32 Comment(0)
W
1

The solution is

instead of using this form

import PIL
PIL.Image

use this form

from PIL import Image
Image

in the Linux system both forms work fine

enter image description here

but in windows, there is a problem

enter image description here

Weakwilled answered 3/6, 2022 at 7:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.