[Python-Dev] Importing .pyc in -O mode and vice versa

Giovanni Bajo rasky at develer.com
Mon Nov 6 20:54:35 CET 2006


Armin Rigo wrote:

> Typical example: someone in the project removes a .py file, and checks
> in this change; someone else does an 'svn up', which kills the .py in
> his working copy, but not the .pyc.  These stale .pyc's cause pain,
> e.g.
> by shadowing the real module (further down sys.path), or simply by
> preventing the project's developers from realizing that they forgot to
> fix some imports.  We regularly had obscure problems that went away as
> soon as we deleted all .pyc files around, but I cannot comment more on
> that because we never really investigated.

This is exactly why I always use this module:

================== nobarepyc.py ============================
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import ihooks
import os

class _NoBarePycHooks(ihooks.Hooks):
    def load_compiled(self, name, filename, *args, **kwargs):
        sourcefn = os.path.splitext(filename)[0] + ".py"
        if not os.path.isfile(sourcefn):
            raise ImportError('forbidden import of bare .pyc file: %r' %
filename)
        return ihooks.Hooks.load_compiled(name, filename, *args, **kwargs)

ihooks.ModuleImporter(ihooks.ModuleLoader(_NoBarePycHooks())).install()
================== /nobarepyc.py ============================

Just import it before importing anything else (or in site.py if you prefer)
and you'll be done.

Ah, it doesn't work with zipimports...
-- 
Giovanni Bajo



More information about the Python-Dev mailing list