Disable use of pyc file with no matching py file

Andrea Crotti andrea.crotti.0 at gmail.com
Tue Jan 31 06:18:47 EST 2012


On 01/30/2012 09:30 PM, Roy Smith wrote:
> Every so often (typically when refactoring), I'll remove a .py file and forget to remove the corresponding .pyc file.  If I then import the module, python finds the orphaned .pyc and happily imports it.  Usually leading to confusing and hard to debug failures.
>
> Is there some way to globally tell python, "Never import a .pyc unless the corresponding .py file exits"?  Perhaps some environment variable I could set in my .login file?

If you want to stay python only I have this function:

def clean_orphaned_pycs(directory, simulate=False):
     """Remove all .pyc files without a correspondent module
     and return the list of the removed files.
     If simulate=True don't remove anything but still return
     the list of pycs
     """

     exists, join = path.exists, path.join
     rm = (lambda _: None) if simulate else remove
     removed = []

     for root, dirs, files in walk(directory):
         for f in files:
             if f.endswith(".pyc"):
                 pyc = join(root, f)
                 if not exists(pyc[:-1]):
                     logger.debug("DELETING orphaned file %s" % pyc)
                     removed.append(pyc)
                     rm(pyc)

         # ignore certain sub-dirs
         for i in reversed(range(len(dirs))):
             d = dirs[i]
             if d == ".svn" or d.endswith(".egg-info"):
                 dirs.pop(i)  # dirs.remove(d)

     return removed




More information about the Python-list mailing list