Created
January 12, 2011 09:36
-
-
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.
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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]