2. WHO AM I?
• Work at indico (small local
company)
• Previously at Olin College,
Pearson, edX, fetchnotes,
and freelance work
• Semi-retired SO & quora user
• Love playing with the dirty
little secrets of python
7. class StubbornObject(object):
def __setattr__(self, key, value):
if hasattr(self, key):
raise ValueError(“Already set in my ways")
else:
object.__setattr__(self, key, value)
>>> test = StubbornObject()
>>> test.a = "one"
>>> test.a = “two” # Now actually errors
ACTUALLY STOPPING PEOPLE FROM TOUCHING
YOUR ATTRIBUTES
9. results = my_object.attribute
if not isinstance(results, list):
results = list(results)
# Do Something
EVER WRITTEN CODE LIKE THIS?
10. class ChangelingObject(object):
list_fields = {"a", "b", "c"}
def __setattr__(self, key, value):
if key in self.list_fields:
value = [value]
object.__setattr__(self, key, value)
>>> test = ChangelingObject()
>>> test.a = 1
>>> print test.a
[1]
NEVER AGAIN WITH SPECIAL PYTHON MAGIC
13. class User(object):
# Standard ORM stuff
def __iadd__(self, other):
current = user_object.balance
try:
user_object.balance = current + other
session.commit()
except ORMException:
session.rollback()
14. def add_money(user_id, amount):
session = Session()
user_object =
session.query(User).filter_by(id=user_id).first()
user_object += amount
SHORT CODE, BUT AT WHAT COST?