Created
October 21, 2010 02:17
-
-
Save rkern/637806 to your computer and use it in GitHub Desktop.
Compile a code snippet while caching its contents.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
import linecache | |
import time | |
import types | |
def code_name(code): | |
""" Compute a (probably) unique name for code for caching. | |
""" | |
hash_digest = hashlib.md5(code).hexdigest() | |
return '<code %s>' % hash_digest | |
class compile_and_cache_code(code): | |
""" Compile some code while caching its contents such that the inspect module can find it later. | |
""" | |
code += '\n' | |
name = code_name(code) | |
code_obj = compile(code, name, 'exec') | |
linecache.cache[name] = (len(code), time.time(), [line+'\n' for line in code.splitlines()], name) | |
return code_obj |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's better to pass
None
instead oftime.time()
. Since Python 2.5 (!) that ensures the line will never be removed from the cache (which is needed since it can't be re-fetched from a file).IPython used to use a horrible monkeypatch to avoid this, when the whole thing was not necessary at all.