Virgiliu
Virgiliu

Reputation: 3118

What happens to memory locations in Python when you overwrite a variable?

In [1]: class T(object):
   ...:     pass
   ...:

In [2]: x = T()

In [3]: print(x)
<__main__.T object at 0x03328E10>

In [4]: x = T()

In [5]: print(x)
<__main__.T object at 0x03345090>

When is the memory location allocated to the first T() object (0x03328E10) freed? Is it when the variable x is overwritten or when the garbage collector is ran or when the script ends?

I'm assuming it's when the garbage collector runs but I don't know how to test that assumption.

Upvotes: 9

Views: 4041

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599610

Python memory management for the most part is done via reference counting, rather than garbage collection. When the reference count goes to zero, the memory is available for reallocation.

The garbage collector only comes into play when you have circular references, which isn't the case here.

Upvotes: 4

minhee
minhee

Reputation: 5818

First of all, it depends on what Python implementation you are using. CPython, the reference implementation, does reference counting, that means your assumption is right. You can test that assumption by implementing __del__ method.

However it’s a bad practice to avoid. For example, PyPy, IronPython, and Jython do garbage collection instead, so your assumption is not guaranteed.

So how can resource finalization be implemented in Python? Use context managers instead. Context managers are RAII feature Python offers.

Upvotes: 2

Related Questions