orenma
orenma

Reputation: 1273

what happens to a dict with no pointer

I have a ponter to a dict() and I keep update it, like that:

def creating_new_dict():
   MyDict = dict()
   #... rest of code - get data to MyDict
   return MyDict

def main():
    while(1):
        MyDict = creating_new_dict()
        time.sleep(20)

I know that MyDict is a pointer to the dict so My question is what happens to the old data in MyDict? Is it deleted or should I make sure it's gone?

Upvotes: 1

Views: 91

Answers (1)

roippi
roippi

Reputation: 25954

Coming back around to answer your question since nobody else did:

I know that MyDict is a pointer to the dict

Ehhh. MyDict is a reference to your dict object, not a pointer. Slight digression follows:


You can't mutate immutable types within a function, because you're handling references, not pointers. See:

def adder(x):
    x = x + 1

a = 0
adder(a)
a
Out[4]: 0

I won't go too far down the rabbit hole, but just this: there is nothing I could have put into the body of adder that would have caused a to change. Because variables are references, not pointers.


Okay, we're back.

so My question is what happens to the old data in MyDict?

Well, it's still there, in some object somewhere, but you blew up the reference to it. The reference is no more, it has ceased to be. In fact, there are exactly zero extant references to the old dict, which will be significant in the next paragraph!

Is it deleted

It's not deleted per se, but you could basically think of it as deleted. It has no remaining references, which means it is eligible for garbage collection. Python's gc, when triggered, will come along and get rid of all the objects that have no remaining references, which includes all your orphaned dicts.

But like I said in my comment: gc will not be triggered -now-, but some time in the (possibly very near) future. How soon that happens depends on.. stuff, including what flavor of python you're running. cPython (the one you're probably running) will usually gc the object immediately, but this is not guaranteed and should not be relied upon - it is left up to the implementation. What you can count on - the gc will come along and clean up eventually. (well, as long as you haven't disabled it)

or should I make sure it's gone?

Nooooo. Nope. Don't do the garbage collector's job. Only when you have a very specific performance reason should you do so.

I still don't believe you, show me an example.

Er, you said that, right? Okay:

class DeleteMe:
    def __del__(self): #called when the object is destroyed, i.e. gc'd
        print(':(')

d = DeleteMe() 
d = DeleteMe() # first one will be garbage collected, leading to sad face
:(

And, like I said before, you shouldn't count on :( happening immediately, just that gc will happen eventually.

Upvotes: 5

Related Questions