pythonreloadimp

Make python reload() function read from .py instead of .pyc


I have written a rather large module which is automatically compiled into a .pyc file when I import it.

When I want to test features of the module in the interpreter, e.g., class methods, I use the reload() function from the imp package.

The problem is that it reloads the .pyc file, not the .py file.

For example I try a function in the interpreter, figure out that it is not working properly, I would make changes to the .py file. However, if I reload the module in the interpreter, it reloads the .pyc file so that the changes are not reflected in the interpreter. I would have to quit the interpreter, start it again and use import to load the module (and create the .pyc file from the .py file). Or alternatively I would have to delete the .pyc file each time.

Is there any better way? E.g., to make reload() prefer .py files over .pyc files?

Here is an except from the interpreter session that shows that reload() loads the .pyc file.

>>> reload(pdb)
<module 'pdb' from 'pdb.pyc'>

EDIT: And even if I delete the .pyc file, another .pyc file will be created each time I use reload, so that I have to delete the .pyc file each time I use reload.

>>> reload(pdb)
<module 'pdb' from 'pdb.py'>
>>> reload(pdb)
<module 'pdb' from 'pdb.pyc'>

Solution

  • yes. here are things you can use the -B command line option:

    python -B
    

    or use the PYTHONDONTWRITEBYTECODE environment option:

    export PYTHONDONTWRITEBYTECODE=1
    

    these make sure the .pyc files are not generated in the first place.