import bug

kj no.email at please.post
Sat Oct 31 16:12:21 CET 2009




I'm running into an ugly bug, which, IMHO, is really a bug in the
design of Python's module import scheme.  Consider the following
directory structure:

ham
|-- __init__.py
|-- re.py
`-- spam.py

...with the following very simple files:

% head ham/*.py
==> ham/__init__.py <==

==> ham/re.py <==

==> ham/spam.py <==
import inspect

I.e. only ham/spam.py is not empty, and it contains the single line
"import inspect".

If I now run the innocent-looking ham/spam.py, I get the following
error:

% python26 ham/spam.py
Traceback (most recent call last):
  File "ham/spam.py", line 1, in <module>
    import inspect
  File "/usr/local/python-2.6.1/lib/python2.6/inspect.py", line 35, in <module>
    import string
  File "/usr/local/python-2.6.1/lib/python2.6/string.py", line 122, in <module>
    class Template:
  File "/usr/local/python-2.6.1/lib/python2.6/string.py", line 116, in __init__
    'delim' : _re.escape(cls.delimiter),
AttributeError: 'module' object has no attribute 'escape'

or, similarly,

% python3 ham/spam.py
Traceback (most recent call last):
  File "ham/spam.py", line 1, in <module>
    import inspect
  File "/usr/local/python-3.0/lib/python3.0/inspect.py", line 36, in <module>
    import string
  File "/usr/local/python-3.0/lib/python3.0/string.py", line 104, in <module>
    class Template(metaclass=_TemplateMetaclass):
  File "/usr/local/python-3.0/lib/python3.0/string.py", line 98, in __init__
    'delim' : _re.escape(cls.delimiter),
AttributeError: 'module' object has no attribute 'escape'

My sin appears to be having the (empty) file ham/re.py.  So Python
is confusing it with the re module of the standard library, and
using it when the inspect module tries to import re.

I've tried a lot of things to appease Python on this one, including
a liberal sprinkling of "from __future__ import absolute_import"
all over the place (except, of course, in inspect.py, which I don't
control), but to no avail.

I also pored over pp. 149-151 of Beazley's Python Essential Reference
(4th ed.) on anything that would shed light on this problem, and
again, nothing.

I give up: what's the trick?  (Of course, renaming ham/re.py is
hardly "the trick."  It's rather Procrustes' Bed.)

BTW, it is hard for me to imagine of an argument that could convince
me that this is not a design bug, and a pretty ugly one at that.
But, as they say, "hope springs eternal": is there a PEP on the
subject?  (I know that there's a PEP on absolute_import, but since
absolute_import appears to be absolutely ineffectual here, I figure
I must look elsewhere for enlightenment.)

TIA!

kynn



More information about the Python-list mailing list