Reducing import try/except boilerplate

Nick Coghlan ncoghlan at iinet.net.au
Wed Dec 21 09:44:52 EST 2005


Several standard library modules (e.g., cPickle/pickle, cStringIO/StringIO, 
threading/dummy_threading) have versions which may not be available on all 
platforms, and pure Python fallbacks that work on any platform Python 
supports. Flicking through the latest version of the Python Cookbook, I 
noticed many recipes that included module fallback suggestions along the lines of:

try:
   import cPickle as pickle
except ImportError:
   import pickle

try:
   import threading
except ImportError
   import dummy_threading as threading

That seems rather verbose for something that isn't that uncommon ("these 
module all expose the same API, so just give me one of them in this order of 
preference"). So what about:

import cPickle or pickle as pickle
import threading or dummy_threading as threading
# 'as' clause required since Python can't guess the name the programmer wants

Also:

   from threading or dummy_threading import Thread
   # No 'as' clause needed since the module name isn't bound


Insomnia-induced-random-ideas-are-fun-'ly yours,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org



More information about the Python-list mailing list