Neuneck
Neuneck

Reputation: 334

If I rassign a variable, will the object it referred to before be deleted?

If I were to run

class Myclass():
    def __init__(self, value):
        self.value = value

var1 = Myclass(1) # initializes the first instance of Myclass
var1 = Myclass(2) # initializes the second instance of Myclass

would the first instance of Myclass linger around in memory? Would the garbage collector (?) free up the space? Do I have to call del var1 to properly free the memory at runtime?

The background of my question is that I run a large loop where in every iteration I need a different instance of a specific class. While I call del explicitly at the moment, it would be nice to know the default behaviour.

Upvotes: 0

Views: 35

Answers (2)

GPhilo
GPhilo

Reputation: 19123

TL;DR: Overwriting var1 with a new object will decrease the reference counter of the original object referenced by var1. If the reference count of an object is zero, the object is destroyed (according to this answer).

The actual answer is a lot more complex than this, and I don't think I feel comfortable delving too much in depth with the explanation (hopefully someone will step in or point you to another question, I'm fairly certain this is a duplicate).

The problem is, Python's garbage collector is implementation-dependent and even in one implementation it can adopt different policies.

Upvotes: 3

Frank AK
Frank AK

Reputation: 1781

When you declaration a new instance your will got different memory space, you can simple check it by id() build-in function.

In [2]: id( Myclass(1))
Out[2]: 4481511576

In [3]: id( Myclass(1))
Out[3]: 4481591488

So, back to your question, if you run multi-times inside your loop. you have to alloc/dealloc memory each time! That's sadly, so if you really want keep the speed up. you can make your object as simple as you can by define __slots__ to keep your object simple even can be fly! check this how to play with slots

Upvotes: 1

Related Questions