473,791 Members | 3,090 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I create a dict that sets a flag if it's been modified

I can think of several messy ways of making a dict that sets a flag if
it's been altered, but I have a hunch that experienced python
programmers would probably have an easier (well maybe more Pythonic)
way of doing this.

It's important that I can read the contents of the dict without
flagging it as modified, but I want it to set the flag the moment I add
a new element or alter an existing one (the values in the dict are
mutable), this is what makes it difficult. Because the values are
mutable I don't think you can tell the difference between a read and a
write without making some sort of wrapper around them.

Still, I'd love to hear how you guys would do it.

Thanks,
-Sandra

Jan 12 '06 #1
11 2080
Ideally, I would have made a wrapper to add/delete/modify/read from
the dictionay.

But other than this, one way i can think straight off is to "pickle"
the dict, and to see if the picked object is same as current object.

cheers,
amit.

On 12 Jan 2006 01:15:38 -0800, sa***********@y ahoo.com
<sa***********@ yahoo.com> wrote:
I can think of several messy ways of making a dict that sets a flag if
it's been altered, but I have a hunch that experienced python
programmers would probably have an easier (well maybe more Pythonic)
way of doing this.

It's important that I can read the contents of the dict without
flagging it as modified, but I want it to set the flag the moment I add
a new element or alter an existing one (the values in the dict are
mutable), this is what makes it difficult. Because the values are
mutable I don't think you can tell the difference between a read and a
write without making some sort of wrapper around them.

Still, I'd love to hear how you guys would do it.

Thanks,
-Sandra

--
http://mail.python.org/mailman/listinfo/python-list

--
----
Endless the world's turn, endless the sun's spinning
Endless the quest;
I turn again, back to my own beginning,
And here, find rest.
Jan 12 '06 #2
sa***********@y ahoo.com writes:
Still, I'd love to hear how you guys would do it.


Make a subclass of dict, or an object containing a dictionary, that
has a special __setattr__ method that traps updates and sets that
modification flag. There are contorted ways the caller can avoid
triggering the flag, but Python is not Java and it in general makes no
attempt to protect its objects against hostile code inside the
application.

Your suggestion of using pickle is shaky in my opinion, since pickle's
docs don't guarantee that pickling the same dictionary twice will
return the same pickle both times. If it happens to work that way,
it's just an implementation accident.
Jan 12 '06 #3
sa***********@y ahoo.com said unto the world upon 12/01/06 03:15 AM:
I can think of several messy ways of making a dict that sets a flag if
it's been altered, but I have a hunch that experienced python
programmers would probably have an easier (well maybe more Pythonic)
way of doing this.

It's important that I can read the contents of the dict without
flagging it as modified, but I want it to set the flag the moment I add
a new element or alter an existing one (the values in the dict are
mutable), this is what makes it difficult. Because the values are
mutable I don't think you can tell the difference between a read and a
write without making some sort of wrapper around them.

Still, I'd love to hear how you guys would do it.

Thanks,
-Sandra


Hi Sandra,

here's one attempt. (I'm no expert, so wait for better :-)
class ModFlagDict(dic t): def __init__(self, *args, **kwargs):
super(ModFlagDi ct, self).__init__( *args, **kwargs)
self.modified = False
def __setitem__(sel f, key, value):
self.modified = True
super(ModFlagDi ct, self).__setitem __(key, value)

md = ModFlagDict(a=4 , b=5)
md {'a': 4, 'b': 5} md.modified False md[3]=5
md {'a': 4, 3: 5, 'b': 5} md.modified True
It's broken in at least one way:
newmd = ModFlagDict(3=4 , 1=5) SyntaxError: keyword can't be an expression


So, as it stands, no integers, floats, tuples, etc can be keys on
initialization. I think that can be be worked around by catching the
exceptions and setting the desired key-value pairs that way. But, it
is almost 4am, and I also suspect there is a much better way I am not
thinking of :-)

Best,

Brian vdB
Jan 12 '06 #4
Brian van den Broek said unto the world upon 12/01/06 03:42 AM:
sa***********@y ahoo.com said unto the world upon 12/01/06 03:15 AM:
I can think of several messy ways of making a dict that sets a flag if
it's been altered, but I have a hunch that experienced python
programmers would probably have an easier (well maybe more Pythonic)
way of doing this.
<snip>
here's one attempt. (I'm no expert, so wait for better :-)
>>> class ModFlagDict(dic t): def __init__(self, *args, **kwargs):
super(ModFlagDi ct, self).__init__( *args, **kwargs)
self.modified = False
def __setitem__(sel f, key, value):
self.modified = True
super(ModFlagDi ct, self).__setitem __(key, value)
<snip>
It's broken in at least one way:
>>> newmd = ModFlagDict(3=4 , 1=5) SyntaxError: keyword can't be an expression >>>
So, as it stands, no integers, floats, tuples, etc can be keys on
initialization. I think that can be be worked around by catching the
exceptions and setting the desired key-value pairs that way. But, it
is almost 4am, and I also suspect there is a much better way I am not
thinking of :-)


Sorry for the self-reply, but I just realized my original code isn't
quite so bad as:

# class ModFlagDict as before
mdict = ModFlagDict({42 :"This will work", (7, 6):"Python comes through, again!"}) mdict {42: 'This will work', (7, 6): 'Python comes through, again!'} mdict.modified False mdict[42]=":-)"
mdict {42: ':-)', (7, 6): 'Python comes through, again!'} mdict.modified True


I'll wager someone will point out a better way still, though.

Best,

Brian vdB
Jan 12 '06 #5
Should the dict flag when the dict itself has been updated? Or also
when any of the items in the dict has been updated?

Say you have a dict consisting of lists...

The dict should be flagged as modified when an item is added; or when
an item is replaced (you call dict.__setitem_ _ with a key that already
exists).
This is clear, and easy to achieve with a simple wrapper or subclass.

But should the dict also be flagged as 'modified' when I append an item
to one of the lists that is in the dict?
l = d['a']
l.append('1')

Does that code mean that the dict should be flagged as 'modified' in
your use-case? or not?

If yes, then the only feasible way might be to pickle the dict. And if
repeated pickling of the same dict is not guaranteed to give the same
results, then perhaps pickling d.getitems() would give the right
results since, AFAIK, dict.getitems() is at least guaranteed to
maintain the same order given that A) The dict is not changed and B)
You're using the same Python version.

Right?

Jan 12 '06 #6
sa***********@y ahoo.com wrote:
It's important that I can read the contents of the dict without
flagging it as modified, but I want it to set the flag the moment I add
a new element or alter an existing one (the values in the dict are
mutable), this is what makes it difficult. Because the values are
mutable I don't think you can tell the difference between a read and a
write without making some sort of wrapper around them.

Detecting when a dictionary is updated is easy, just subclass dict and
override the __setitem__ method.

Detecting when an object contained within the dictionary is mutated is
effectively impossible.

If you are willing to compromise you can do something similar to the
solution used in the ZODB (persistent object database): it marks an object
as dirty when you rebind an attribute, but it doesn't attempt to catch
mutation of contained objects. If you want a contained dictionary or list
to be handled automatically by the persistence machinery you can use a
PersistentDict or PersistentList object, otherwise you can use an ordinary
dict/list and manually flag the container as dirty when you mutate it.

This leads to code such as (assuming self is the container):

....
self.somelist.a ppend(something )
self.somelist = self.somelist

which isn't wonderful but mostly works. Of course:

self.somelist += [something]

also has the desired effect.
Jan 12 '06 #7
On Thu, 12 Jan 2006 03:42:21 -0600,
Brian van den Broek <br***@cc.umani toba.ca> wrote:
It's broken in at least one way:
newmd = ModFlagDict(3=4 , 1=5) SyntaxError: keyword can't be an expression So, as it stands, no integers, floats, tuples, etc can be keys on
initialization ...


That has nothing to do with your code:
dict(1=4) SyntaxError: keyword can't be an expression int(4=5)

SyntaxError: keyword can't be an expression

The names of keyword arguments have look like Python identifiers; 1 and
4 are *not* valid Python identifiers.

Regards,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
Jan 12 '06 #8
Brian van den Broek <br***@cc.umani toba.ca> writes:
It's broken in at least one way:
>>> newmd = ModFlagDict(3=4 , 1=5)

SyntaxError: keyword can't be an expression


newmd = ModFlagDict(**{ 3:4, 1:5})
Jan 12 '06 #9
Paul Rubin wrote:
sa***********@y ahoo.com writes:
Still, I'd love to hear how you guys would do it.

Make a subclass of dict, or an object containing a dictionary, that
has a special __setattr__ method that traps updates and sets that


/__setattr__/__setitem__/ ?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Jan 12 '06 #10

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

Similar topics

8
2153
by: bearophileHUGS | last post by:
I'm frequently using Py2.4 sets, I find them quite useful, and I like them, even if they seem a little slower than dicts. Sets also need the same memory of dicts (can they be made to use less memory, not storing values? Maybe this requires too much code rewriting). I presume such sets are like this because they are kind of dicts. If this is true, then converting a dict to a set (that means converting just the keys; this is often useful for...
5
3641
by: me | last post by:
I have a Class Library that contains a Form and several helper classes. A thread gets created that performs processing of data behind the scenes and the Form never gets displayed (it is for debug puposes only and is not normally visable to the user.) The Thread function is actually in the Form class. Now.. What I am seeing is that when I create an instance of this Class Library's Form, which starts the worker thread, it seems to hose up...
11
1952
by: mwt | last post by:
Hi. I'm reworking a little app I wrote, in order to separate the data from the UI. As a start, I wanted to create a iron-clad data recepticle that will hold all the important values, and stand up to being queried by various sources, perhaps concurrently. In all likelihood, the app will never need anything that robust, but I want to learn to write it anyway, as an exercise. So here is my code. It's really simple, and I'm sure you can see my...
3
24362
by: Gregory Piñero | last post by:
Hey guys, I don't understand why this isn't working for me. I'd like to be able to do this. Is there another short alternative to get this intersection? >>> set().intersection() Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: dict objects are unhashable
37
3312
by: Steven Bethard | last post by:
The PEP below should be mostly self explanatory. I'll try to keep the most updated versions available at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html PEP: XXX Title: The create statement
18
2723
by: Steven Bethard | last post by:
I've updated the PEP based on a number of comments on comp.lang.python. The most updated versions are still at: http://ucsu.colorado.edu/~bethard/py/pep_create_statement.txt http://ucsu.colorado.edu/~bethard/py/pep_create_statement.html In this post, I'm especially soliciting review of Carl Banks's point (now discussed under Open Issues) which asks if it would be better to have the create statement translated into:
3
7167
by: weston | last post by:
I'm making a foray into trying to create custom vertical scrollbars and sliders, and thought I had a basic idea how to do it, but seem to be having some trouble with the implementation. My thinking was: (a) create a div for the slider / scroll nub to move within (b) attach event handlers which, onmousedown, specify the slider/nub is moveable, and onmouseup, specify it's not (c) attach an event handler to the contaning div which,...
1
2279
by: bearophileHUGS | last post by:
The PEP 3100: http://www.python.org/dev/peps/pep-3100/ says: Return iterators instead of lists where appropriate for atomic type methods (e.g. dict.keys(), dict.values(), dict.items(), etc.); iter* methods will be removed. Better: make keys(), etc. return views ala Java collections??? .... To be removed:
6
2648
by: kaens | last post by:
Hey everyone, this may be a stupid question, but I noticed the following and as I'm pretty new to using xml and python, I was wondering if I could get an explanation. Let's say I write a simple xml parser, for an xml file that just loads the content of each tag into a dict (the xml file doesn't have multiple hierarchies in it, it's flat other than the parent node) so we have <parent>
0
9669
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
9515
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10427
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...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10155
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
9029
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
4110
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
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
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.