Skip to content

Instantly share code, notes, and snippets.

@saxix
Created December 23, 2013 21:00
Show Gist options
  • Save saxix/8104473 to your computer and use it in GitHub Desktop.
Save saxix/8104473 to your computer and use it in GitHub Desktop.
context manager to temporary set/delete object's attributes
DELETE_ATTRIBUTE = object()
@contextmanager
def attributes(*values):
""" context manager to temporary set/delete object's attributes
:param values: tulples of (target, name, value)
Es.
with attributes((django.contrib.admin.ModelAdmin, 'list_per_page', 200)):
...
with attributes((django.contrib.admin.ModelAdmin, 'list_per_page', DELETE_ATTRIBUTE)):
...
"""
def set(target, name, value):
if value is DELETE_ATTRIBUTE:
delattr(target, name)
else:
setattr(target, name, value)
backups = []
for target, name, value in values:
backups.append((target, name, getattr(target, name, DELETE_ATTRIBUTE)))
set(target, name, value)
yield
for target, name, value in backups:
set(target, name, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment