From e2d1b8ae0d5b7854fb26484efa53ee07c7889a12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Barrag=C3=A1n=20Merino?= Date: Sun, 17 Nov 2013 16:09:06 +0100 Subject: [PATCH] Created a method decorator to change temporarily the value of an attribute to the instance --- greenmine/base/decorators.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 greenmine/base/decorators.py diff --git a/greenmine/base/decorators.py b/greenmine/base/decorators.py new file mode 100644 index 00000000..0ee28751 --- /dev/null +++ b/greenmine/base/decorators.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +from functools import wraps + +def change_instance_attr(name, new_value): + """ + Change the attribute value temporarily for a new one. If it raise an AttributeError (if the + instance hasm't the attribute) the attribute will not be changed. + """ + def change_instance_attr(fn): + @wraps(fn) + def wrapper(instance, *args, **kwargs): + try: + old_value = instance.__getattribute__(name) + changed = True + except AttributeError: + changed = False + + if changed: + instance.__setattr__(name, new_value) + + ret = fn(instance, *args, **kwargs) + + if changed: + instance.__setattr__(name, old_value) + + return ret + return wrapper + return change_instance_attr +