Skip to content

Instantly share code, notes, and snippets.

@philpennock
Created January 12, 2011 09:36
Show Gist options
  • Save philpennock/775939 to your computer and use it in GitHub Desktop.
Save philpennock/775939 to your computer and use it in GitHub Desktop.
Demo of Python one-time eval of function declaration default params, used for caching.
def foo(a, b=None, cache={}):
if b is not None:
cache[a] = b
return b
if a in cache:
return cache[a]
raise KeyError('Bleh, no %s' % a)
@philpennock
Copy link
Author

Grabbed this snippet to test gist.

Note that normally using a mutable object as a default value for a function param is a bad idea, but this is the rare case where it's the correct approach and turns what's normally a programming bug into a neat hack. [The default value is evaluated when the function definition is executed, not when the function is invoked, and the result is used for each call to the function]

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