473,799 Members | 3,350 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

scared about refrences...

I'm really worried that python may is doing some things I wasn't
expecting... but lets see...

if I pass a list to a function def fn(myList):

and in that function I modify an element in the list, then does the
callers list get modied as well.

def fn(list):
list[1] = 0

myList = [1, 2, 3]
print myList
fn(myList)
print myList
>>[1,2,3]
[1,0,3]
How can I avoid this? In this case this is a really simplified example
but the effects are the same...
How do I specify or create deep copies of objects that may contain
other objects that may contain other
object that may contain other objects....

Oct 30 '06
28 1233
I think you are afraid of references because you are not trusting your
own code. You are afraid it will do "magic" behind the scenes and mess
everything up. One way around that is to simply write better code and
test often.

If everything was copied when passed around it would be pretty awful --
imagine passing around a 1Gb worth of data to a function...

In Python all the primitives are copied and all other entities are
references. If you want to just copy a list you can :
1) use the list class: new_list=list(o ld_list)
2) use the [:] syntax: new_list=old_li st[:]
3) if your list has nested lists, for example, the above methods will
not copy everything, so you need a deep copy -- copy.deepcopy()

Hope this helps,
Nick V.
SpreadTooThin wrote:
I'm really worried that python may is doing some things I wasn't
expecting... but lets see...

if I pass a list to a function def fn(myList):

and in that function I modify an element in the list, then does the
callers list get modied as well.

def fn(list):
list[1] = 0

myList = [1, 2, 3]
print myList
fn(myList)
print myList
>[1,2,3]
[1,0,3]

How can I avoid this? In this case this is a really simplified example
but the effects are the same...
How do I specify or create deep copies of objects that may contain
other objects that may contain other
object that may contain other objects....
Oct 30 '06 #11

J. Clifford Dyer wrote:
SpreadTooThin wrote:
Steven D'Aprano wrote:
On Mon, 30 Oct 2006 13:10:47 -0800, SpreadTooThin wrote:

How do I specify or create deep copies of objects that may contain
other objects that may contain other object that may contain other
objects... .
See the `copy` module especially `copy.deepcopy( )`.

This appears to be the right thing to do to me.. (but what do I know?)
Yes, copy.deepcopy() is the thing you want.

But remember Fredrik's advice that well-designed Python code should not
need to copy data structures often. I don't think I've ever needed to use
deepcopy, and rarely copy.copy().

In general, functions should not modify their caller's data. So this is
bad practice:

def print_list(alis t):
"""Print a sorted list"""
alist.sort() # modifies the caller's data -- bad!
for index, value in enumerate:
print "Value %s at index %d" % (index, value)

This is better:

def print_list(alis t):
"""Print a sorted list"""
alist = alist[:] # makes a local shallow copy of the list
alist.sort() # safe to modify now
for index, value in enumerate:
print "Value %s at index %d" % (index, value)

But notice that you only need a shallow copy, not a deep copy, because you
aren't modifying the objects within the list, only the list itself.

I tried this which more closely resembles my project but this doesn't
work:
Unfortunately my crystal ball is back at the shop being repaired, so
you'll have to explain what "doesn't work" means in this case. Does it
raise an exception? If so, please post the exception. Does it do something
different from what you expected? Then what did you expect, and what did
it do?
I seems that some of the objects in the list don't get along well with
deep copy..
See my second example post that used deepcopy... When run blows up...
When it blows up, is there a lot of shrapnel, or just smoke and fire?
Is the shrapnel mostly metal, or is it plastic and glass?

In short, if we don't know what's happening, we can't help.
* Did the program spit out a bunch of text you didn't understand?
If so, show us the text. That text may be incomprehensibl e at first,
but it contains crucial clues.

* Did it close your python window without a word?
Tell us.

* Did your computer freeze up?
Tell us.

If you don't tell us what went wrong *exactly*, you won't get a
satisfactory answer.
I would assume that looking at the code you should be able to tell..
Silly me.. Here.. is the log.. If I were helping.. I would have cut
and pasted the code myself and ran it.. instead of trying to interpret
this...

array('H', [1, 2, 3]) ['a', 'b', 'c']
Traceback (most recent call last):
File
"/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
line 1806, in runMain
self.dbg.runfil e(debug_args[0], debug_args)
File
"/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
line 1529, in runfile
h_execfile(file , args, module=main, tracer=self)
File
"/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
line 590, in __init__
execfile(file, globals, locals)
File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py",
line 20, in __main__
test(t)
File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py",
line 16, in test
t = copy.deepcopy(x )
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 174, in deepcopy
y = copier(x, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 305, in _deepcopy_inst
state = deepcopy(state, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 174, in deepcopy
y = copier(x, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 268, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 185, in deepcopy
y = copier(x, memo)
TypeError: __deepcopy__() takes no arguments (1 given)
Cheers,
Cliff
Oct 31 '06 #12
At Monday 30/10/2006 20:37, Nick Vatamaniuc wrote:
>In Python all the primitives are copied and all other entities are
references.
What do you mean?
primitives==bui ltin classes?
entities==objec ts?
In Python, objects are never automatically copied, either builtin or
user-defined. Even 123 is an object. Names provide references to objects.
Perhaps you were thinking of *another* language.
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Oct 31 '06 #13
SpreadTooThin wrote:
J. Clifford Dyer wrote:
>SpreadTooThi n wrote:
>>Steven D'Aprano wrote:
On Mon, 30 Oct 2006 13:10:47 -0800, SpreadTooThin wrote:
I seems that some of the objects in the list don't get along well with
deep copy..
See my second example post that used deepcopy... When run blows up...
When it blows up, is there a lot of shrapnel, or just smoke and fire?
Is the shrapnel mostly metal, or is it plastic and glass?

In short, if we don't know what's happening, we can't help.
* Did the program spit out a bunch of text you didn't understand?
If so, show us the text. That text may be incomprehensibl e at first,
but it contains crucial clues.

* Did it close your python window without a word?
Tell us.

* Did your computer freeze up?
Tell us.

If you don't tell us what went wrong *exactly*, you won't get a
satisfactory answer.

I would assume that looking at the code you should be able to tell..
Silly me.. Here.. is the log.. If I were helping.. I would have cut
and pasted the code myself and ran it.. instead of trying to interpret
this...
I know it seems unnecessary to post the traceback when I could get the
same thing by running your code on my machine, but it's actually useful,
for a couple reasons: First, when I run the code, I might not get an
error, or if I do, it might not be the same error you were getting, and
then we'd be on a wild goose chase. This could be because your python
installation is goofy, or because you copied in your code incorrectly.
Shit happens, and I'd rather not even start down one of those blind
alleys. Third, it provides a useful frame for how to look at your
code. While a traceback might look like a big mess at first, it's
actually pretty easy to skim through once you get used to it, and it
tells me where to focus my attention in your code.
>
array('H', [1, 2, 3]) ['a', 'b', 'c']
Traceback (most recent call last):
File
"/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
line 1806, in runMain
self.dbg.runfil e(debug_args[0], debug_args)
File
"/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
line 1529, in runfile
h_execfile(file , args, module=main, tracer=self)
File
"/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
line 590, in __init__
execfile(file, globals, locals)
File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py",
line 20, in __main__
test(t)
File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py",
line 16, in test
t = copy.deepcopy(x )
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 174, in deepcopy
y = copier(x, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 305, in _deepcopy_inst
state = deepcopy(state, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 174, in deepcopy
y = copier(x, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 268, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 185, in deepcopy
y = copier(x, memo)
TypeError: __deepcopy__() takes no arguments (1 given)
>Cheers,
Cliff
Thanks, that's very helpful. Playing with your code a bit, I narrowed
the problem down to the array.array() structure. Looking at
help(array), there's a method defined called __deepcopy__, which, it
seems, takes no arguments, while deepcopy is passing it one argument.
Looks like a bug in the array module to me. Maybe others with more
experience using array will have some deeper insight.
Cheers,
Cliff
Oct 31 '06 #14
J. Clifford Dyer wrote:
Thanks, that's very helpful.**Playi ng*with*your*co de*a*bit,*I*nar rowed
the problem down to the array.array() structure.**Loo king*at
help(array), there's a method defined called __deepcopy__, which, it
seems, takes no arguments, while deepcopy is passing it one argument.
Looks like a bug in the array module to me.**Maybe*othe rs*with*more
Fixed in subversion: http://www.python.org/sf/1545837

Oct 31 '06 #15

J. Clifford Dyer wrote:
SpreadTooThin wrote:
J. Clifford Dyer wrote:
SpreadTooThin wrote:
Steven D'Aprano wrote:
On Mon, 30 Oct 2006 13:10:47 -0800, SpreadTooThin wrote:
I seems that some of the objects in the list don't get along well with
deep copy..
See my second example post that used deepcopy... When run blows up...

When it blows up, is there a lot of shrapnel, or just smoke and fire?
Is the shrapnel mostly metal, or is it plastic and glass?

In short, if we don't know what's happening, we can't help.
* Did the program spit out a bunch of text you didn't understand?
If so, show us the text. That text may be incomprehensibl e at first,
but it contains crucial clues.

* Did it close your python window without a word?
Tell us.

* Did your computer freeze up?
Tell us.

If you don't tell us what went wrong *exactly*, you won't get a
satisfactory answer.
I would assume that looking at the code you should be able to tell..
Silly me.. Here.. is the log.. If I were helping.. I would have cut
and pasted the code myself and ran it.. instead of trying to interpret
this...

I know it seems unnecessary to post the traceback when I could get the
same thing by running your code on my machine, but it's actually useful,
for a couple reasons: First, when I run the code, I might not get an
error, or if I do, it might not be the same error you were getting, and
then we'd be on a wild goose chase. This could be because your python
installation is goofy, or because you copied in your code incorrectly.
Shit happens, and I'd rather not even start down one of those blind
alleys. Third, it provides a useful frame for how to look at your
code. While a traceback might look like a big mess at first, it's
actually pretty easy to skim through once you get used to it, and it
tells me where to focus my attention in your code.

array('H', [1, 2, 3]) ['a', 'b', 'c']
Traceback (most recent call last):
File
"/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
line 1806, in runMain
self.dbg.runfil e(debug_args[0], debug_args)
File
"/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
line 1529, in runfile
h_execfile(file , args, module=main, tracer=self)
File
"/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py",
line 590, in __init__
execfile(file, globals, locals)
File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py",
line 20, in __main__
test(t)
File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py",
line 16, in test
t = copy.deepcopy(x )
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 174, in deepcopy
y = copier(x, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 305, in _deepcopy_inst
state = deepcopy(state, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 174, in deepcopy
y = copier(x, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 268, in _deepcopy_dict
y[deepcopy(key, memo)] = deepcopy(value, memo)
File
"/Library/Frameworks/Python.framewor k/Versions/2.4/lib/python2.4/copy.py",
line 185, in deepcopy
y = copier(x, memo)
TypeError: __deepcopy__() takes no arguments (1 given)
Cheers,
Cliff

Thanks, that's very helpful. Playing with your code a bit, I narrowed
the problem down to the array.array() structure. Looking at
help(array), there's a method defined called __deepcopy__, which, it
seems, takes no arguments, while deepcopy is passing it one argument.
Looks like a bug in the array module to me. Maybe others with more
experience using array will have some deeper insight.

I don't understand why python would insist that everything must be a
refrence...
It is of course helpful sometime but other times its not... and now
I'm sorta out
of luck...
I don't know how to make this structure immutable... Pickle it? Seems
very
inefficient to me...
Every time I pass a variable now I will worry that it will be changed
by the function...
I haven't worried about things like this since the very early days of
BASIC....
I don't know.. maybe I have more to learn.

Cheers,
Cliff
Oct 31 '06 #16
I don't know how to make this structure immutable... Pickle
it? Seems very inefficient to me...
Well, classes can be made mostly immutable by intercepting the
attempts to write to it...something like

class Foo(object):
def __setattr__( self, name, val ):
raise TypeError("I'm sorry, Dave. You can't do that.")

It might also be feasible to do something like this with a
decorator...?
Every time I pass a variable now I will worry that it will be
changed by the function... I haven't worried about things like
this since the very early days of BASIC.... I don't know..
maybe I have more to learn.
Well, there are at least solutions to this paranoia that occur to me:

-make a deep-copy of the object in question before calling the
function, and then pass the copy to the function so that it can't
alter the original

-trust/read the functions' documentation. Most functions that
alter the contents of their parameters are kind enough to note as
much. If functions go bunging with your parameters without
documenting it, the function's coder needs to be smacked.

-tkc


Oct 31 '06 #17
At Tuesday 31/10/2006 14:16, SpreadTooThin wrote:
>I don't understand why python would insist that everything must be a
refrence...
It is of course helpful sometime but other times its not... and now
I'm sorta out
of luck...
I don't know how to make this structure immutable... Pickle it? Seems
very
inefficient to me...
Every time I pass a variable now I will worry that it will be changed
by the function...
I haven't worried about things like this since the very early days of
BASIC....
I don't know.. maybe I have more to learn.
If you haven't read this yet, you should:
<http://www.effbot.org/zone/python-objects.htm>
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Oct 31 '06 #18
SpreadTooThin wrote:
Every time I pass a variable now I will worry that it will be changed
by the function...
why? who's writing those scary functions that you cannot trust? and
what makes you think they won't abuse any immutable data you give them?

</F>

Oct 31 '06 #19
SpreadTooThin wrote:
[...]
I don't understand why python would insist that everything must be a
refrence...
We can tell that :)
It is of course helpful sometime but other times its not... and now
I'm sorta out
of luck...
There are very good reasons for Python's namespace model. Sure it's
different from some other languages, but it's actually been some
people's preferred semantics for a very long time now (the
recently-deceased Ralph Griswold, may he rest in peace, chose a very
similar model for Icon.
I don't know how to make this structure immutable... Pickle it? Seems
very
inefficient to me...
Every time I pass a variable now I will worry that it will be changed
by the function...
I haven't worried about things like this since the very early days of
BASIC....
I don't know.. maybe I have more to learn.
You do. Firstly, learn to leave your paranoia outside your programming
life. If a function or method makes undocumented changes to its mutable
parameters then it needs changing (or its documentation does).

Adequate testing should reveal such nonsenses before release.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Oct 31 '06 #20

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

Similar topics

0
1087
by: Lawrence Oluyede | last post by:
http://www.cardboard.nu/archives/000118.html I think that the guy (Alan Green) is very scared :) I read also a funny (but clever) comment to that post (the first one): " True, True. In fact, we should boycott Java, too. C is the way to go! (Or Assembler? Or just write the binary code by hand?) "
3
1373
by: Lawrence Oluyede | last post by:
http://www.cardboard.nu/archives/000118.html I think that the guy (Alan Green) is very scared :) I read also a funny (but clever) comment to that post (the first one): " True, True. In fact, we should boycott Java, too. C is the way to go! (Or Assembler? Or just write the binary code by hand?) "
0
1093
by: sonic_soul | last post by:
hi i have a solution with 22 loaded projects. 1 of those projects is a web app, and this web app is using functionality from the other 21 projects which are simple dll's in my web project i need to add a refrence to other projects so that the dll's are automatically copied to my web app/bin directory. i can do that for all but a couple of them..
0
900
by: Josh | last post by:
Hi Guys, I have lots of web refrences connecting to different sites and i need to be able to dynamically call the web refrence based on output from a database. At the moment i am doing the following; //send execution command to the client to update the database wrAmp.dbExecutor dbe = new wrAmp.dbExecutor(); bool barf = dbe.updateDatabase();
3
1569
by: Afshar | last post by:
Hi, I am writing a single .cs in IDE that uses some refrences that I have created previously as dll. I compile this refrences with /r switch in csc.exe with no problem. IntelliSense works with cs commands and syntaxes. But the problem is It doesn't know my own refrences and so doesn't show my class members. What can I do with with these? Please Help! Regards,
0
9688
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
9544
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
10490
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
10238
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
10030
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4145
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
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.