How to guard against bugs like this one?

Tim Chase python.list at tim.thechases.com
Mon Feb 1 22:33:10 EST 2010


Stephen Hansen wrote:
> First, I don't shadow built in modules. Its really not very hard to avoid.

Given the comprehensive nature of the batteries-included in 
Python, it's not as hard to accidentally shadow a built-in, 
unknown to you, but yet that is imported by a module you are 
using.  The classic that's stung me enough times (and many others 
on c.l.p and other forums, as a quick google evidences) such that 
I *finally* remember:

   bash$ touch email.py
   bash$ python
   ...
   >>> import smtplib
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "/usr/lib/python2.5/smtplib.py", line 46, in <module>
       import email.Utils
   ImportError: No module named Utils

Using "email.py" is an innocuous name for a script/module you 
might want to do emailish things, and it's likely you'll use 
smtplib in the same code...and kablooie, things blow up even if 
your code doesn't reference or directly use the built-in email.py.

Yes, as Chris mentions, PEP-328 absolute vs. relative imports 
should help ameliorate the problem, but it's not yet commonly 
used (unless you're using Py3, it's only at the request of a 
__future__ import in 2.5+).

-tkc







More information about the Python-list mailing list