[Python-Dev] Syntax suggestion for imports
Jeroen Ruigrok van der Werven
asmodai at in-nomine.org
Thu Jan 3 10:08:42 CET 2008
-On [20080103 08:53], Raymond Hettinger (python at rcn.com) wrote:
>Thanks. I'm more curious about the content of those lines. Does the
>proposed syntax help, does the need go away in Py3.0, what is the typical
>pattern?
These are some of the examples, I've tried to reduce them to specific use
patterns:
To determine if some feature is available:
try:
pygments = __import__('pygments', {}, {}, [])
have_pygments = True
except ImportError:
have_pygments = False
try:
from docutils import nodes
from docutils.core import publish_parts
from docutils.parsers import rst
from docutils import __version__
except ImportError:
raise TracError(_('Docutils not found'))
if StrictVersion(__version__) < StrictVersion('0.3.9'):
raise TracError(_('Docutils version >= %(version)s required, '
'%(found)s found', version='0.3.9', found=__version__))
To specify which specific version we have of a given module:
try:
import pysqlite2.dbapi2 as sqlite
have_pysqlite = 2
except ImportError:
try:
import sqlite3 as sqlite
have_pysqlite = 2
except ImportError:
try:
import sqlite
have_pysqlite = 1
except ImportError:
have_pysqlite = 0
This gets repeated a lot in order to see if we have threading:
try:
import threading
except ImportError:
import dummy_threading as threading
threading._get_ident = lambda: 0
Functions we do use and need, fall-back to support code if not present:
try:
from operator import attrgetter, itemgetter
except ImportError:
def attrgetter(name):
def _getattr(obj):
return getattr(obj, name)
return _getattr
def itemgetter(name):
def _getitem(obj):
return obj[name]
return _getitem
Masking functions if a particular function is not found:
try:
from base64 import b64decode
except ImportError:
from base64 import decodestring as b64decode
--
Jeroen Ruigrok van der Werven <asmodai(-at-)in-nomine.org> / asmodai
イェルーン ラウフロック ヴァン デル ウェルヴェン
http://www.in-nomine.org/ | http://www.rangaku.org/
Only I can change my life. No one can do it for me...
More information about the Python-Dev
mailing list