DeepSpace
DeepSpace

Reputation: 81664

Are datetime objects cached?

I was tinkering around what it would take to get False from

print(datetime.now() == datetime.now())

I suppose that on every 'modern'/fast enough computer this will be True.

However, I've noticed something peculiar:

print(id(datetime.now()) == id(datetime.now()))

Will constantly output True, which led me to believe that datetime objects (probably just those created by .now()) are automagically cached somewhere.

Then I tinkered a bit more, and came up with this gem:

def get_now():
    now = datetime.now()
    print(id(now))
    return now

print(get_now() == get_now())
exit()

Now we get different IDs and the output is constantly False, as if the overhead of calling get_now twice was enough for the caching mechanism to understand the time changed and a new object was needed to be created.

I looked around at datetime.py and couldn't find anything that will explain this behavior, so I suppose (if it even exists) it is implemented in the C level.

The word "cache" (or any of its conjugates) is not mentioned at all on the official datetime docs.

Upvotes: 3

Views: 389

Answers (1)

Barmar
Barmar

Reputation: 782107

There's no caching going on. Your code is roughly equivalent to:

temp = datetime.now()
id1 = id(temp)
temp = None
temp = datetime.now()
id2 = id(temp)
print(id1 == id2)

Clearing the variable after getting the ID allows the first datetime object to be garbage collected. The second datetime object reuses that memory, so they get the same ID.

If you write instead

temp1 = datetime.now()
temp2 = datetime.now()
print (id(temp1) == id(temp2))

you'll see that they're different.

Upvotes: 6

Related Questions