Do datetime objects need to be deep-copied?

Question:

So I noticed the other week through running an experiment, that, despite being a high-level language, while you can make copies of variables by just assigning them like this:

a = 5    
b = a
print(b) # 5
b = 3
print(b) # 3
print(a) # 5

…if you treat dictionaries or possibly lists the same way, it comes unstuck! I created a bug in my code the other week thinking that dictionaries worked the same way.. Found out that to make a proper, deep copy you need to go:

b = dict(a)

Anyway, I’m busy with datetime objects and I’m manipulating them around as if they were integers, now starting to get a bit nervous as to whether this is okay. It all seems a bit arbitrary where it works and where it doesn’t, do I have to run an experiment every time just to check its behaviour? Can guess that strings probably work like integers but not sure where the behaviour changes.

Can see someone has asked about this for PHP but for Python I’m inclined to think that any assignment of a datetime object would be a proper, deep copy and never mess accidentally with the original variable. Does anyone know for sure?

Asked By: cardamom

||

Answers:

There is nothing arbitrary about this.

All assignments in Python are references. No copying is ever done on assignment.

If you have the ability to mutate the object then any mutation will naturally affect all the references to that object.

The only reason you don’t see this with integers or strings in your original code is that you’re not mutating the objects, you’re simply reassigning. Integers and strings, as well as datetimes, don’t have any way of being mutated, so the only thing you can do is reassign them. If you reassigned a list, dict, or datetime, then you would not see the change propagated to other references, either.

Answered By: Daniel Roseman

Since all available types in the datetime module are documented as being immutable (right after the documentation of the classes it is stated):

Objects of these types are immutable.

you shouldn’t worry about this.

Operations on a datetime instance will return a new instance thereby not affecting any other names that refer to the previous one.

You might want to take a look at the link provided by PM 2Ring that explains facts and myths about how names and values work. That should shed some light on any confusions you have about names.

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.