[Python-Dev] Syntax suggestion for imports (original) (raw)

Raymond Hettinger python at rcn.com
Thu Jan 3 04:29:28 CET 2008


[GvR]

I wonder if your perceived need for this isn't skewed by your working within the core?

The need was perceived by a colleague who does not work on the core. My own skew was in the opposite direction -- I've seen the pattern so often that I'm oblivious to it.

Before posting, I ran some scans of our code base at work and found plenty of examples (mostly third-party cmodules vs python equivalents and a few that searched for similar functionality in different packages). It might be helpful if others were to also search their own code bases and post their findings:

find . -name "*py" | xargs grep -C2 ImportError *py

Also, Google's codesearch gives some examples (and a lot of cases that really do need the try/except form):

http://www.google.com/codesearch?q=+lang:python+%22except+ImportError%22

I was surprised to see many examples in the form of:

try: import xyz except ImportError: xyz = None

I was also surprised to find plenty of code that is likely to be buggy because the two alternative loaded different names:

try: from Products.OpenPT.OpenPTFile import OpenPTFile as ptFile except ImportError: from Products.PageTemplates.PageTemplateFile import PageTemplateFile

I was not surprised to see searches for similar functionality across different packages like kjbuckets vs kjbuckets0 , Zope vs Zope2, or HTMLParser vs SGMLParser, or attempts to load any of several packages compliant with the DBAPI.

Surely, Py3.0's automatic vectoring to C equivalent modules will help with the cases like cStringIO, cPickle. I don't think it will help with the general case of searching for a best available package (like gdbm vs dbm vs dumbdbm or threading vs dummythreading) or a best available implementation of a single function (like twisted.protocols._c_urlarg.unquote vs urllib.unquote or one of the various implementations of date utilities or encryption functions).

Am curious to see what everyone else finds in their own code searches.

[John Barham]

This I find more problematic as "emptymodule" seems too magical. . . . try: readline = None import readline except ImportError: pass

Perhaps "import readline or None" would have been a better way to capture that pattern as well as the "except pass" pattern.

Raymond



More information about the Python-Dev mailing list