@contextlib.contextmanager
def swap_attr(obj, attr, new_val):
 if hasattr(obj, attr):
  real_val = getattr(obj, attr)
  setattr(obj, attr, new_val)
  try:
   (yield)
  finally:
   setattr(obj, attr, real_val)
 else:
  setattr(obj, attr, new_val)
  try:
   (yield)
  finally:
   delattr(obj, attr)

@ contextlib . contextmanager def swap_attr ( obj , attr , new_val ) : if hasattr ( obj , attr ) : real_val = getattr ( obj , attr ) setattr ( obj , attr , new_val ) try : ( yield ) finally : setattr ( obj , attr , real_val ) else : setattr ( obj , attr , new_val ) try : ( yield ) finally : delattr ( obj , attr )
temporary swap out an attribute with a new object .