Skip to content

Instantly share code, notes, and snippets.

@horacioibrahim
Last active August 29, 2015 14:07
Show Gist options
  • Save horacioibrahim/6bd3f43ea52f33acc764 to your computer and use it in GitHub Desktop.
Save horacioibrahim/6bd3f43ea52f33acc764 to your computer and use it in GitHub Desktop.
Handling a dict in our class
"""
Simple code for to show when is need to use copy()
"""
class MyObj(object):
# ... hide ...
def save(self, document, id_field="_id"):
"""
Uses update if not exist insert rather update the object
Args:
document -> a dictionary with MongoDB's syntax to save it
id_field -> name of field it'll indexed. Default is _id
"""
# TODO: support multiple indexes (unique with fields)
# collection = self.db
# Removing a value of dict
try:
_id = document[id_field]
del document[id_field]
except KeyError, e:
raise TypeError("The method save() required an arg id_field or the "
"key _id in document") # TODO: create exceptions
try:
# collection.update({'_id': _id}, {'$set': new_doc},
#upsert=True)
return 0
except:
raise
obj = MyObj()
# My dict
d = {'_id': 1, 'a': 'data'}
obj.save(d)
# What will happen?
print d['_id']
@horacioibrahim
Copy link
Author

Existem melhorias que podem ser realizadas neste trecho de código. Porém uma mudança é extremamente necessária para evitar colisão ;). Qual é? O que precisamos fazer para melhorar esse código adicionando somente uma linha?

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