Fix for “import Image” ImportError with pillow

Tags: python, django

Pillow is a better-packaged version of PIL, the Python Imaging Library. There’s one problem you can see, though, and that’s with importing. PIL allowed both import Image and from PIL import Image. Pillow sanely only supports the second version.

A colleague had a problem earlier today with TileStache that used the old import Image version. And that fails with Pillow. The solution I suggested him was to add a little hack at the top of a file that’s loaded early in the process (in this case a Django settings file was the best spot):

import sys
from PIL import Image
sys.modules['Image'] = Image

This makes sure you get PIL.Image when you do import Image afterwards. Problem solved.

Note: if both of the imports work for you without this hack, it can be a good idea to check if you need to clean something up. Import both versions and check their __file__ attribute:

>>> from PIL import Image
>>> Image.__file__
'/usr/lib/python2.7/dist-packages/PIL/Image.pyc'
>>> import Image
>>> Image.__file__
'/usr/lib/python2.7/dist-packages/PIL/Image.pyc'

In my case, I only have PIL, apparently. The colleague had a different result for the first import: that one was from Pillow, the second from PIL. Something to keep in mind if you have weird PIL-related results.

 
vanrees.org logo

Reinout van Rees

My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):