15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

[id(x) for x in hubby]<br />

[9919616, 11826320]<br />

>>> [id(x) for x in wifey]<br />

[9919616, 11826320]<br />

AFTER:<br />

>>> [id(x) for x in hubby]<br />

[12092832, 11826320]<br />

>>> [id(x) for x in wifey]<br />

[12191712, 11826320]<br />

If the intention was to create a joint account for the couple, then we have a great solution, but if we<br />

want separate accounts, we need to change something. In order to obtain a full or deep copy of the<br />

objectcreating a new container but containing references to completely new copies (references) of the<br />

element in the original objectwe need to use the copy.deepcopy() function. Let us redo the entire<br />

example but using deep copies instead:<br />

>>> person = ['name', ['savings', 100.00]]<br />

>>> hubby = person<br />

>>> import copy<br />

>>> wifey = copy.deepcopy(person)<br />

>>> [id(x) for x in person, hubby, wifey]<br />

[12242056, 12242056, 12224232]<br />

>>> hubby[0] = 'joe'<br />

>>> wifey[0] = 'jane'<br />

>>> hubby, wifey<br />

(['joe', ['savings', 100.0]], ['jane', ['savings', 100.0]])<br />

>>> hubby[1][1] = 50.00<br />

>>> hubby, wifey<br />

(['joe', ['savings', 50.0]], ['jane', ['savings', 100.0]])<br />

Now it is just the way we want it. For kickers, let us confirm that all four objects are different:<br />

>>> [id(x) for x in hubby]<br />

[12191712, 11826280]<br />

>>> [id(x) for x in wifey]<br />

[12114080, 12224792]<br />

There are a few more caveats to object copying. The first is that non-container types (i.e., numbers,<br />

strings, and other "atomic" objects like code, type, and xrange objects) are not copied. Shallow copies of<br />

sequences are all done using complete slices. Finally, deep copies of tuples are not made if they contain<br />

only atomic objects. If we changed the banking information to a tuple, we would get only a shallow copy<br />

even though we asked for a deep copy:<br />

>>> person = ['name', ('savings', 100.00)]<br />

>>> newPerson = copy.deepcopy(person)<br />

>>> [id(x) for x in person, newPerson]<br />

[12225352, 12226112]<br />

>>> [id(x) for x in person]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!