简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM