Skip to content

Instantly share code, notes, and snippets.

@nubela
Created March 14, 2013 11:12
Show Gist options
  • Save nubela/5160540 to your computer and use it in GitHub Desktop.
Save nubela/5160540 to your computer and use it in GitHub Desktop.
Python: Exploiting gotchas for caching
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