473,768 Members | 8,326 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

trap setting attribute when the attribute is dict

Hello all,

I have a question which might be simple or need some work around.

I want to do something like this. My class/instance has a dict as a
property. I want the instance to catch the change in the dict (change
in some values, addition/deletion of key/value etc) to be recognized by
the class instance.

How can I do this? Any suggestions are very well appreciated.

Here is an example of what I want my class to behave:

class test(object):
def __init__(self):
self._d = {}
self._changed = False
def getd(self):
print 'called getd'
return self._d
# dont know what to do next
def setd(self,val):
print 'called setd', key, val
self._d[key] = val
self._changed = True
d = property(getd,s etd,None,None)

def getc(self):
return self._changed
changed = property(getc,N one,None,None)

if __name__ == '__main__':
obj = test()
print 'obj.changed = ', obj.changed
print

# I want obj to know that its propety d being changed here
print "t.d['a'] = 1"
obj.d['a'] = 1
print

# I want the "changed" property to be True
print 'obj.changed = ', obj.changed



--
yosuke kimura
Center for Energy and Environmental Resources
The Univ. of Texas at Austin, USA
Sep 3 '07 #1
1 1621
John Machin <sj******@lexic on.netwrote:
On Sep 4, 5:47 am, <yos...@ccwf.cc .utexas.eduwrot e:
>Arnaud Delobelle <arno...@google mail.comwrote:
On Sep 3, 7:00 pm, <yos...@ccwf.cc .utexas.eduwrot e:
>I want to do something like this. My class/instance has a dict as a
property. I want the instance to catch the change in the dict (change
in some values, addition/deletion of key/value etc) to be recognized by
the class instance.
>How can I do this? Any suggestions are very well appreciated.
[snip]
>>
Thank you for suggestion, Arnaud.

Since you are discouraging this idea of trigger, may I ask an advice of
if my intention was legitimate one or not?

My intention was to have a propery 'sum' in my object, and which has sum
of all the values() of the dict (i have code to make sure that the value
of dict are all numeric). I could just the propery being calculated
everytime the property got __getattr__. But I thought that it was
inefficient to calculate the same number over and over when the value is
already known. So I was thiking of calculating the number only when the
dict got modified.

I also experimented with the idea of subclassing dict itself to
calculate the sum. Is this what would be better solution?
And what's wrong with calculating the value when you need it ...
def thedictsum(self ):
return sum(self.thedic t.itervalues())
How big will the dict be, how often will it be updated, how often will
the sum be required?
Have you done timings of any of the options?
Thank you for the post.

I want the code to have fewer lines of code. That was my biggest
motivation for this. I have many of this dict with sum, each have <1000
elements. all of them share the same keys. I do many
addition/subtraction/divisions by each elements (yes, division makes the
elements not being able to summed). so in my code i have repeated lines
that works on each elements and then on the sum. i made a dict to take
care of adding elements by elements. but i still had two lines of code,
one for dict elements, and one for the sum.

my code was originally in fortran and it has like thousands of lines,
obscuring the mathematics that i want to do. i need to modify math
often while i use the code (i dont know exactly what math i will need at
this point), so i want to the code to be able to show the math
clearly. ideally i want to this to be somthing like

c = a + b
d = 1 / c

and each of a, b, c, d knows how to operates on each elements, and also
keep track of the sum.

I think i will settle for extending dict to have sum property and keep
track of it .


You say you have code to check that the values are numeric; why not
put this together with maintenance of the sum into a method which
clients must use to update the dict?
BTW, my motto:
"__" == "Danger, Will Robinson!" == "Wrong way, go back" :-)

not quite getting this.... :(
HTH,
John

--
yosuke kimura
Center for Energy and Environmental Resources
The Univ. of Texas at Austin, USA
Sep 4 '07 #2

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

Similar topics

2
2155
by: GrelEns | last post by:
hello, i would like if this behaviour can be obtained from python : trap an attributeError from inside a subclassing dict class... (here is a silly examples to explain my question) class Test(dict): """subclassing a dict and each key will permit access to a tuple of fized size""" def __init__(self):
1
1995
by: svilen | last post by:
hi. this was named but it is misleading. i want to have the order of setting items in intrinsic dicts (keyword args, or class attributes, etc). which is, a prdered dict trhat matches the source-text sequences.
6
1760
by: the.theorist | last post by:
I have a small, simple class which contains a dictionary (and some other stuff, not shown). I then have a container class (Big) that holds some instances of the simple class. When I try to edit the elements of the dictionary, all instances obtain those changes; I want each instance to hold separate entries. #----------Begin module test.py class ex: def __init__(self, val={}): self.value = val
1
1310
by: jslowery | last post by:
Hmm, I know this is something fundamental about how Python implements predicate dispatch, but for some reason I believed that this would work: class delegate_dict(dict): def __init__(self, orig, deleg): dict.__init__(self, orig) self.deleg = deleg def __getitem__(self, name):
10
2360
by: pemo | last post by:
As far as I understand it, a trap representation means something like - an uninitialised automatic variable might /implicitly/ hold a bit-pattern that, if read, *might* cause a 'trap' (I'm not sure what 'a trap' means here - anyone?). I also read into this that, an *initialised* automatic variable, may never hold a bit pattern that might, when read, cause a 'trap'. I.e., if an auto is explicitly initialised, it may *never* hold a...
3
1576
by: 7stud | last post by:
"When you bind (on either a class or an instance) an attribute whose name is not special...you affect only the __dict__ entry for the attribute(in the class or instance, respectively)." In light of that statement, how would one explain the output of this code: class Test(object): x =
5
1399
by: feli.hp | last post by:
Hello all, Imaybe someone can help me with this question. Is there a direct way of accessing an object instance, if all I know is the value of one of its attributes? The object is part of a list of objects, and I would like to pick the object directly by using this attribute value, instead of going through the list and checking if each objects attribute value is the one I am looking for.
6
3557
by: Adam Donahue | last post by:
As an exercise I'm attempting to write a metaclass that causes an exception to be thrown whenever a user tries to access 'attributes' (in the traditional sense) via a direct reference. Consider: class X( object ): y = 'private value' def get_y( self ): return self.y
12
1232
by: Joshua Kugler | last post by:
OK, I'm sure the answer is staring me right in the face--whether that answer be "you can't do that" or "here's the really easy way--but I am stuck. I'm writing an object to proxy both lists (subscriptable iterables, really) and dicts. My init lookslike this: def __init__(self, obj=None): if type(obj).__name__ in 'list|tuple|set|frozenset': self.me =
0
9576
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10175
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9961
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8840
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7384
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5425
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3932
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3534
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2808
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.