Skip to content

Instantly share code, notes, and snippets.

@rkern
Created October 21, 2010 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rkern/637806 to your computer and use it in GitHub Desktop.
Save rkern/637806 to your computer and use it in GitHub Desktop.
Compile a code snippet while caching its contents.
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
@o11c
Copy link

o11c commented Oct 4, 2022

It's better to pass None instead of time.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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment