attribute save restore

Carsten Haese carsten at uniqsys.com
Fri Apr 13 21:41:34 CEST 2007


On Fri, 2007-04-13 at 14:08 -0500, Carl K wrote:
> Is there a more elegant way of coding this:
> 
> x=o.p  # save .p
> o.p=0
> o.m()
> o.p=x  # restore .p

In Python 2.5, you could leverage the new "with" statement with a
properly crafted context manager along these lines:

"""
from __future__ import with_statement

class TempAttrSetter(object):
  def __init__(self, obj, **attrs):
    self.obj = obj
    self.attrs = attrs

  def __enter__(self):
    self.saved_attrs = {}
    for attr, newval in self.attrs.iteritems():
      self.saved_attrs[attr] = getattr(self.obj, attr)
      setattr(self.obj, attr, newval)

  def __exit__(self, *args):
    for attr in self.saved_attrs.keys():
      setattr(self.obj, attr, self.saved_attrs[attr])

class Bag(object): pass
b = Bag()
b.x = 1

print b.x                    # prints 1
with TempAttrSetter(b, x=3):
  print b.x                  # prints 3
print b.x                    # prints 1
"""

-Carsten





More information about the Python-list mailing list