473,322 Members | 1,562 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

attribute save restore

Is there a more elegant way of coding this:

x=o.p # save .p
o.p=0
o.m()
o.p=x # restore .p

seems very push/pop to me - like there should be a way that doesn't need a var
(x) or the save/set lines should be done in one command.

(personally I think .m would better be implemented by passing in a parameter,
but that isn't my choice.)

Carl K
Apr 13 '07 #1
4 1325
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

seems very push/pop to me - like there should be a way that doesn't need
a var (x) or the save/set lines should be done in one command.
With the appropriate context manger, you could write this as::

with setting(o, 'p', 2):
o.m()

Here's the code::
>>from __future__ import with_statement
@contextlib.contextmanager
... def setting(obj, name, value):
... old_value = getattr(obj, name)
... setattr(obj, name, value)
... try:
... yield obj
... finally:
... setattr(obj, name, old_value)
...
>>class C(object):
... def __init__(self, x):
... self.x = x
... def m(self):
... print self.x
...
>>c = C(1)
with setting(c, 'x', 2):
... c.m()
...
2
>>print c.x
1

Of course, that just wraps up the same push/pop behavior you're doing
into a context manager.
(personally I think .m would better be implemented by passing in a
parameter, but that isn't my choice.)
Yep, that's the right answer. You should complain to whoever created
this API.

STeVe
Apr 13 '07 #2
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
Apr 13 '07 #3
Steven Bethard wrote:
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

seems very push/pop to me - like there should be a way that doesn't
need a var (x) or the save/set lines should be done in one command.

With the appropriate context manger, you could write this as::

with setting(o, 'p', 2):
o.m()

Here's the code::
>>from __future__ import with_statement
>>@contextlib.contextmanager
... def setting(obj, name, value):
... old_value = getattr(obj, name)
... setattr(obj, name, value)
... try:
... yield obj
... finally:
... setattr(obj, name, old_value)
...
>>class C(object):
... def __init__(self, x):
... self.x = x
... def m(self):
... print self.x
...
>>c = C(1)
>>with setting(c, 'x', 2):
... c.m()
...
2
>>print c.x
1

Of course, that just wraps up the same push/pop behavior you're doing
into a context manager.
Thanks.

As I was eating lunch I came up with:

x,o.p = o.p,0

Which I am pretty sure is just bad :)
I need to cut back on the hot sauce.
>
>(personally I think .m would better be implemented by passing in a
parameter, but that isn't my choice.)

Yep, that's the right answer. You should complain to whoever created
this API.
Will do. Something is buggy anyway, so as long as I am commenting...

Carl K
Apr 13 '07 #4
Carl K a écrit :
Is there a more elegant way of coding this:

x=o.p # save .p
o.p=0
o.m()
o.p=x # restore .p

seems very push/pop to me - like there should be a way that doesn't need
a var (x) or the save/set lines should be done in one command.

(personally I think .m would better be implemented by passing in a
parameter, but that isn't my choice.)
I was about to comment on this. It looks like o.m is wanting to take an
optional arg defaulting to o.p, and you should probably propose a patch
to the author.

My 2 cents

Apr 13 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Dave Romig | last post by:
Can anyone provide guidance for saving and restoring an XMLDOM object as a binary blob? In a VB application, I need to repeatedly save and restore a large, dynamic XML document. Currently, the...
0
by: Reinhard Vornholt | last post by:
Hi, I am trieing to save the complete viewstate of a page and restore it at a later point. That should work like this: - Someone leaves the page and switches to an other page in the same...
14
by: fdu.xiaojf | last post by:
Hi, I have a program which will continue to run for several days. When it is running, I can't do anything except waiting because it takes over most of the CUP time. Is it possible that the...
2
by: Fabrizio Pollastri | last post by:
My code is the following: from Tkinter import * def tk_dummy_call(*args): return root = Tk() # save call address
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.