Neinstein
Neinstein

Reputation: 1033

Why do my Python PIL imports not working?

When I am working with the PIL, I have to import a tons of PIL modules. I was experimenting with three ways to do this, but only the last one works despite all is being logical to me:

Importing the complete PIL and calling it's modules in the code: NOPE

>>> import PIL
>>> image = PIL.Image.new('1', (100,100), 0) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'

Importing everything from PIL: NOPE

>>> from PIL import *
>>> image = Image.new('1', (100,100), 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Image' is not defined 

importing some modules from PIL: OK

>>> from PIL import Image
>>> image = Image.new('1', (100,100), 0)
>>> image
<PIL.Image.Image image mode=1 size=100x100 at 0xB6C10F30>
>>> # works...

What did I not get here?

Upvotes: 7

Views: 1648

Answers (1)

miradulo
miradulo

Reputation: 29680

PIL doesn't import any submodules on it's own. This is actually pretty common.

So when you use from PIL import Image, you actually locate the Image.py file and import that, whereas when you attempt to just call PIL.Image after import PIL, you're attempting an attribute lookup on an empty module (since you didn't import any submodules).

The same reasoning applies for why from PIL import * won't work - you need to explicitly import the Image submodule. In any case, from ... import * is seen as bad practice due to the namespace pollution that will occur - your best bet is to use from PIL import Image.

Further, PIL is no longer being maintained, but for backwards compatibility purposes should you use from PIL import Image you can ensure your code will remain compatible with the still-maintained Pillow (as oppposed to just using import Image).

Upvotes: 3

Related Questions