Created
December 23, 2013 21:00
-
-
Save saxix/8104473 to your computer and use it in GitHub Desktop.
context manager to temporary set/delete object's attributes
This file contains hidden or 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
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