import bug

Carl Banks pavlovevidence at gmail.com
Mon Nov 2 19:52:27 EST 2009


On Oct 31, 7:12 am, kj <no.em... at please.post> wrote:
> 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.


Python is documented as behaving this way, so this is not a bug.

It is arguably poor design.  However, Guido van Rossum already ruled
against using a single package for the standard library, and its not
likely that special case code to detect accidental name-clashes with
the standard library is going to be added, since there are legitimate
reasons to override the standard library.

So for better or worse, you'll just have to deal with it.


Carl Banks



More information about the Python-list mailing list