@contextlib.contextmanager
def temporary_mutation(obj, **kwargs):
 NOT_PRESENT = object()
 old_values = {}
 for (attr, new_value) in kwargs.items():
  old_values[attr] = getattr(obj, attr, NOT_PRESENT)
  setattr(obj, attr, new_value)
 try:
  (yield)
 finally:
  for (attr, old_value) in old_values.items():
   if (old_value is NOT_PRESENT):
    del obj[attr]
   else:
    setattr(obj, attr, old_value)

@ contextlib . contextmanager def temporary_mutation ( obj , ** kwargs ) : NOT_PRESENT = object ( ) old_values = { } for ( attr , new_value ) in kwargs . items ( ) : old_values [ attr ] = getattr ( obj , attr , NOT_PRESENT ) setattr ( obj , attr , new_value ) try : ( yield ) finally : for ( attr , old_value ) in old_values . items ( ) : if ( old_value is NOT_PRESENT ) : del obj [ attr ] else : setattr ( obj , attr , old_value )
temporarily set the attr on a particular object to a given value then revert when finished .