I'm trying to understand a weird behavior when using datetime inside python's dictionary. Code below is written to explain. I expected that the example of variable a and b will act the same as self.x and self.y.
To be more clear: at the beginning self.x=1,self.y=2, later on self.x=self.y, and inside a while loop - self.x is getting incremented by 1. As expected, only self.x is reaching the value of 5, while self.y remains at 2 as shown in run result below.
BUT I'm looking for an explanation why it is not happening with a, b which both increase by datetime.timedelta(days=3) while only b is was coded to be incremented.
Any explaintion why ?
class TBD:
def __init__(self):
self.x = 1
self.y = 2
print(self.x, self.y)
self.run_it()
def run_it(self):
self.x = self.y
z = 0
a = {'start': datetime.datetime.now(), 'end': datetime.datetime.now() + datetime.timedelta(days=1)}
b = a
while z < 3:
self.x += 1
z += 1
b['end'] = b['end'] + datetime.timedelta(days=3)
print(b['end'], a['end'])
print('x=', self.x, 'y=', self.y)
Run results:
1 2
2018-05-15 16:26:58.101727 2018-05-15 16:26:58.101727
x= 3 y= 2
2018-05-18 16:26:58.101727 2018-05-18 16:26:58.101727
x= 4 y= 2
2018-05-21 16:26:58.101727 2018-05-21 16:26:58.101727
x= 5 y= 2
Process finished with exit code 0
b = adoes not create a copy, and there's a fundamental difference between mutable objects like dictionaries and immutable objects like integers. (Note this is nothing to do with datetime.)x = {0:1}; y = x; x[0] = 2; print(y)and see that mutating x also mutates y.