Apparent magic number problem

Peter Otten __peter__ at web.de
Sat Mar 9 03:51:31 EST 2013


Colin J. Williams wrote:
> The program runs correctly under each version, but it runs more slowly 
> under 3.2.

> This is probably due to the fact that the .pyc file is created for the
> Python 2.7 execution.
 
> When Python 3.2 is run it fails to create a new .pyc file and if the 2.7
> .pyc is offered directly a magic number problem is reported.

(1) .pyc files are only created if a module is imported
(2) The 2.7 .pyc file is put alongside the .py file whereas the 3.2 .pyc is 
put into the __pycache__ subfolder. No clash can occur.

A simple example:

$ ls
mod.py
$ cat mod.py
print("hello world")

Run it; no pyc is created:

$ python2.7 mod.py
hello world
$ ls
mod.py

Import it using 2.7:

$ python2.7 -c 'import mod'
hello world
$ ls
mod.py  mod.pyc

Import it using 3.2:

$ python3.2 -c 'import mod'
hello world
$ ls
mod.py  mod.pyc  __pycache__
$ ls __pycache__/
mod.cpython-32.pyc

Run the compiled code:

$ python2.7 mod.pyc
hello world
$ python3.2 __pycache__/mod.cpython-32.pyc 
hello world

But I'm with Steven, it's unlikely that the module compilation phase is 
responsible for a noticeable slowdown.





More information about the Python-list mailing list