[Python-Dev] import succeeds on second try?

Guido van Rossum guido@digicool.com
Sat, 10 Feb 2001 21:29:39 -0500


> This is weird:
> 
>     localhost[1118]% ll spam*
>     -rw-r--r--   1 ping     users          69 Feb 10 17:40 spam.py
>     localhost[1119]% ll eggs*
>     /bin/ls: eggs*: No such file or directory
>     localhost[1120]% cat spam.py
>     a = 1
>     print 'hello'
>     import eggs # no such file
>     print 'goodbye'
>     b = 2
>     localhost[1121]% python
>     Python 2.1a2 (#22, Feb 10 2001, 16:15:14) 
>     [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
>     Type "copyright", "credits" or "license" for more information.
>     >>> import spam
>     hello
>     Traceback (most recent call last):
>       File "<stdin>", line 1, in ?
>       File "spam.py", line 3, in ?
>         import eggs # no such file
>     ImportError: No module named eggs
>     >>> import spam
>     >>> dir(spam)
>     ['__builtins__', '__doc__', '__file__', '__name__', 'a']
>     >>>
>     localhost[1122]% ll spam*
>     -rw-r--r--   1 ping     users          69 Feb 10 17:40 spam.py
>     -rw-r--r--   1 ping     users         208 Feb 10 17:41 spam.pyc
>     localhost[1123]% ll eggs*
>     /bin/ls: eggs*: No such file or directory
> 
> Why did Python write spam.pyc after the import failed?

That's standard stuff; happens all the time.

1. The module gets compiled to bytecode, and the compiled bytecode
   gets written to the .pyc file, before any attempt to execute is.

2. The spam module gets entered into sys.modules at the *start* of its
   execution, for a number of reasons having to do with mutually
   recursive modules.

3. The execution fails on the "import eggs" but that doesn't undo the
   sys.modules assignment.

4. The second import of spam finds an incomplete module in
   sys.modyles, but doesn't know that, so returns it.

--Guido van Rossum (home page: http://www.python.org/~guido/)