Thanks! I understand this better now. This is really an example of a more general pattern: @contextmanager def rebind_attr(object_, attr, value): orig = getattr(object_, attr) setattr(object_, attr, value) yield setattr(object_, attr_, orig)