[Python-Dev] bug or feature in imp.load_module()?

Neal Norwitz neal@metaslash.com
Wed, 17 Oct 2001 10:04:36 -0400


module = imp.load_module(path, file, filename, smt)

After returning from imp.load_module(), the file paramter passed in may 
be at the beginning or end depending on whether it was byte compiled.
If the file was already compiled, the file returned will stay at the beginning.
If the file was byte compiled in load_module(), the file will be at the end.

The following program may demonstrate better:

#####################

import imp, sys, os

FILE_BASE = 'x'
PY_FILE = FILE_BASE + '.py'

def load(f):
    file, filename, smt = imp.find_module(f, sys.path)
    imp.load_module('', file, filename, smt)
    print 'File is at byte:', file.tell()

def main():
    try:
        os.unlink(PY_FILE + 'c')
    except:
        pass
    if not os.path.exists(PY_FILE):
        file = open(PY_FILE, 'w')
        file.close()
    load(FILE_BASE)
    load(FILE_BASE)

if __name__ == '__main__':
    main()

#####################

file sometimes being modified was unexpected.  And I couldn't
find the behaviour documented anywhere.

This behaviour goes back to Python 1.5 at least AFAIR.

Neal