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

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to