473,405 Members | 2,349 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,405 software developers and data experts.

Lists & "pointers"

Hello all,

I have written a simple whiteboard application. In my application, I
want to be able to set draw attributes. This part works. I have a
dictionary object which contains stuff like:
self.attr['Pen.Color'] = ...
self.attr['Pen.Thickness'] = ...

Now, the problem is that I want to be able to store attributes in a
list so they'll be easily accessed using the function keys. I.e. I have
the "current attributes" which I want to be able to store or retrieve
in/from a list,

The problem is that I have initialized the list like this:

self.drawAttr = { blah, blah, blah.. }
self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append(self.drawAttr)

I know what the problem is; they are all referencing the *same*
dictionary object. So, my question is: How do I initialize a list of
dictionary objects, where each list entry is its own object (which is a
copy from the self.drawAttr object).

Also, how do I store/restore entries to the list?

I have found the "copy" module, and it's copy method. I assume this
would work:

for i in range(0, 10):
self.storedAttr.append(copy.copy(self.drawAttr))

However, the concept of "deep copy" confuses me. Do I want it, or
don't I want it? I repeat: the attributes object is a simple dictionary.

Thankful for any advice.
Jul 23 '05 #1
5 1585
Jan Danielsson wrote:
Hello all,

I have written a simple whiteboard application. In my application, I
want to be able to set draw attributes. This part works. I have a
dictionary object which contains stuff like:
self.attr['Pen.Color'] = ...
self.attr['Pen.Thickness'] = ...

Now, the problem is that I want to be able to store attributes in a
list so they'll be easily accessed using the function keys. I.e. I have
the "current attributes" which I want to be able to store or retrieve
in/from a list,

The problem is that I have initialized the list like this:

self.drawAttr = { blah, blah, blah.. }
self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append(self.drawAttr)

I know what the problem is; they are all referencing the *same*
dictionary object. So, my question is: How do I initialize a list of
dictionary objects, where each list entry is its own object (which is a
copy from the self.drawAttr object).

Also, how do I store/restore entries to the list?

I have found the "copy" module, and it's copy method. I assume this
would work:

for i in range(0, 10):
self.storedAttr.append(copy.copy(self.drawAttr))

However, the concept of "deep copy" confuses me. Do I want it, or
don't I want it? I repeat: the attributes object is a simple dictionary.

Thankful for any advice.


The easiest way to do it would be to create a new dictionary object for
each iteration of your loop. In this scenario, you would not need to
use the copy module.

In other words:

self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append({ blah, blah, blah.. })

I hope this helps!

Regards,

Michael Loritsch

Jul 23 '05 #2
<ri***@hotmail.com> wrote:
Jan Danielsson wrote:
Hello all,

I have written a simple whiteboard application. In my application, I
want to be able to set draw attributes. This part works. I have a
dictionary object which contains stuff like:
self.attr['Pen.Color'] = ...
self.attr['Pen.Thickness'] = ...

Now, the problem is that I want to be able to store attributes in a
list so they'll be easily accessed using the function keys. I.e. I have
the "current attributes" which I want to be able to store or retrieve
in/from a list,

The problem is that I have initialized the list like this:

self.drawAttr = { blah, blah, blah.. }
self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append(self.drawAttr)

I know what the problem is; they are all referencing the *same*
dictionary object. So, my question is: How do I initialize a list of
dictionary objects, where each list entry is its own object (which is a
copy from the self.drawAttr object).

Also, how do I store/restore entries to the list?

I have found the "copy" module, and it's copy method. I assume this
would work:

for i in range(0, 10):
self.storedAttr.append(copy.copy(self.drawAttr))

However, the concept of "deep copy" confuses me. Do I want it, or
don't I want it? I repeat: the attributes object is a simple dictionary.

Thankful for any advice.


The easiest way to do it would be to create a new dictionary object for
each iteration of your loop. In this scenario, you would not need to
use the copy module.

In other words:

self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append({ blah, blah, blah.. })


And this would be equivalent to shallow copy. Whether you need a deep copy depends on what each
"blah" is. More specifically it depends on whether the values of the dictionary are mutable or not
(the keys are known to be immutable anyway). If they are immutable, a shallow copy is enough. If
not, check whether all dictionaries refer to the same values or separate copies of the values. Only
in the latter case you need deep copy.

HTH,

George
Jul 23 '05 #3
Jan Danielsson wrote:
Hello all,

I have written a simple whiteboard application. In my application, I
want to be able to set draw attributes. This part works. I have a
dictionary object which contains stuff like:
self.attr['Pen.Color'] = ...
self.attr['Pen.Thickness'] = ...

Now, the problem is that I want to be able to store attributes in a
list so they'll be easily accessed using the function keys. I.e. I have
the "current attributes" which I want to be able to store or retrieve
in/from a list,

The problem is that I have initialized the list like this:

self.drawAttr = { blah, blah, blah.. }
self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append(self.drawAttr)

I know what the problem is; they are all referencing the *same*
dictionary object. So, my question is: How do I initialize a list of
dictionary objects, where each list entry is its own object (which is a
copy from the self.drawAttr object).
Hi Jan son of Daniel,

you might initialize self.storedAttr with empty dicts and fill them
later:

self.soredAttr = [{}]*10
for entry in self.storedAttr:
entry.update(self.drawAttr)

Also, how do I store/restore entries to the list?

I have found the "copy" module, and it's copy method. I assume this
would work:

for i in range(0, 10):
self.storedAttr.append(copy.copy(self.drawAttr))

However, the concept of "deep copy" confuses me. Do I want it, or
don't I want it? I repeat: the attributes object is a simple dictionary.

Thankful for any advice.


A *shallow copy* creates a new dictionary and copies the references, a
*deep copy* tries to create a new reference for each existing object in
the dict. The disadvantage of deepcopy is that it does not work in many
cases:
copy.deepcopy([lambda :None]) Traceback (most recent call last):
....
TypeError: function() takes at least 2 arguments (0 given)

As the docs tell:

"This version does not copy types like module, class, function, method,
stack trace, stack frame, file, socket, window, array, or any similar
types."

I wonder if one couldn't pickle a module and reimport it in order to
create a copy of it ;)

IMO this is a weakness of the algorithm. One usually doesn't want to
duplicate a function so that a new reference of a function is not
needed because it is readonly and the algorithm could reuse the same
reference. For classes I don't if the assertion in the docs is actually
true?
class A:pass
copy.deepcopy(A) <class __main__.A at 0x01191990>
class A(object): .... def __init__(self):pass
.... copy.deepcopy(A) <class '__main__.A'>


Regards,
Kay

Jul 23 '05 #4
* Kay Schluehr wrote:
you might initialize self.storedAttr with empty dicts and fill them
later:

self.soredAttr = [{}]*10
for entry in self.storedAttr:
entry.update(self.drawAttr)


As a matter of fact, you're doing the same ;-)

In [1]: x = [{}] * 10

In [2]: x[0]['a'] = 1

In [3]: x[1]['b'] = 2

In [4]: x
Out[4]:
[{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2},
{'a': 1, 'b': 2}]

nd
--
"Umfassendes Werk (auch fuer Umsteiger vom Apache 1.3)"
-- aus einer Rezension

<http://pub.perlig.de/books.html#apache2>
Jul 23 '05 #5
On Sat, 23 Jul 2005 17:03:08 +0200, Jan Danielsson wrote:
The problem is that I have initialized the list like this:

self.drawAttr = { blah, blah, blah.. }
self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append(self.drawAttr)

I know what the problem is; they are all referencing the *same*
dictionary object. So, my question is: How do I initialize a list of
dictionary objects, where each list entry is its own object (which is a
copy from the self.drawAttr object).
self.drawAttr = { blah, blah, blah.. }
self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append(self.drawAttr.copy())

You only need to worry about the difference between copy and deepcopy if
the objects inside the dict are complex objects like dicts and lists.

You also said that: "I want to be able to store attributes in a list so
they'll be easily accessed using the function keys."

I don't think this is good usage. What happens when you change the
attributes in one place but forget to change it in the other?

A better solution would be to set up either a list or a mapping from
function key to attribute, rather than to a COPY of the attribute. Why
change things in two places rather than one?

Something like this:

# set up attributes before hand
self.attr['Pen.Color'] = 'blue'
self.attr['Pen.Thickness'] = 1
self.attr['Pen.State'] = 'down'
# etc
# now point the function keys to attributes
self.functionkeys = {'F1' = 'Pen.Color', 'F2' = 'Pen.Thickness',
'F3' = 'Pen.State', ... }

Then, when you want to access the current value of some attribute, instead
of looking up a list:

# bad way
def get_attribute(fkey):
if fkey = 'F1':
return self.storedAttr[0]
elif fkey = 'F2':
return self.storedAttr[1]
...
elif fkey = 'F12':
return self.storedAttr[11]

you would do something like this:

# good way
def get_attribute(fkey):
return self.attr[self.functionkeys[fkey]]
Also, how do I store/restore entries to the list?
That question is awfully open-ended. Can you be more specific?
I have found the "copy" module, and it's copy method. I assume this
would work:

for i in range(0, 10):
self.storedAttr.append(copy.copy(self.drawAttr))

However, the concept of "deep copy" confuses me. Do I want it, or
don't I want it? I repeat: the attributes object is a simple dictionary.


That depends on what is inside your simple dictionary. For immutable
objects like ints, floats and strings, copy is sufficient:
D1 = {1: 'hello', 2: 'there'}
D1 {1: 'hello', 2: 'there'} D2 = D1.copy()
D1[1] = 'go'
D1 {1: 'go', 2: 'there'} D2 {1: 'hello', 2: 'there'}

See what happens when the values are mutable objects:
DM1 = {1: [0,1], 2: [4, 5]}
DM2 = DM1.copy()
DM1[3] = [0,2]
DM1 {1: [0, 1], 2: [4, 5], 3: [0, 2]} DM2 {1: [0, 1], 2: [4, 5]}

So far so good. But now look:
DM1[1].append(999)
DM1 {1: [0, 1, 999], 2: [4, 5], 3: [0, 2]} DM2

{1: [0, 1, 999], 2: [4, 5]}

The difference is that although copy makes a copy of the top level of the
dict, it DOESN'T make copies of the individual objects within the dict.

This doesn't matter is the objects are immutable, but if they are lists or
other dicts, you can get surprises like the above.
--
Steven.

Jul 24 '05 #6

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

Similar topics

388
by: maniac | last post by:
Hey guys, I'm new here, just a simple question. I'm learning to Program in C, and I was recommended a book called, "Mastering C Pointers", just asking if any of you have read it, and if it's...
46
by: TTroy | last post by:
Hi, I'm just wondering why people/books/experts say "the function returns a pointer to.." or "we have to send scanf a pointer to.." instead of "the function returns the address of.." or "we have...
14
by: Alf P. Steinbach | last post by:
Not yet perfect, but: http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01_examples.zip To access the table of...
24
by: arnuld | last post by:
PURPOSE: see the comments. WHAT I GOT: infinite loop /* This program will simply create an array of pointers to integers * and will fill it with some values while using malloc...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...

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.