Created
March 14, 2013 11:12
-
-
Save nubela/5160540 to your computer and use it in GitHub Desktop.
Python: Exploiting gotchas 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 get_mongo(db=[]): | |
""" | |
This function employs a good ol` gotcha with using mutable objects as a default value for an argument to cache | |
the database object. | |
If the `db` arg is an empty list, populate it with the object. | |
Every other call to this function will skip the if clause and return the cached `db` object. | |
Win. | |
""" | |
if db == []: | |
connection = MongoClient(MONGO_HOST, MONGO_PORT) | |
mongo_db = connection[MONGO_DB] | |
db += [mongo_db] | |
return db[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment