Tutorial by Examples

The vast majority of Python memory management is handled with reference counting. Every time an object is referenced (e.g. assigned to a variable), its reference count is automatically increased. When it is dereferenced (e.g. variable goes out of scope), its reference count is automatically decreas...
The only time the garbage collector is needed is if you have a reference cycle. The simples example of a reference cycle is one in which A refers to B and B refers to A, while nothing else refers to either A or B. Neither A or B are accessible from anywhere in the program, so they can safely be dest...
Removing a variable name from the scope using del v, or removing an object from a collection using del v[item] or del[i:j], or removing an attribute using del v.name, or any other way of removing references to an object, does not trigger any destructor calls or any memory being freed in and of itsel...
An interesting thing to note which may help optimize your applications is that primitives are actually also refcounted under the hood. Let's take a look at numbers; for all integers between -5 and 256, Python always reuses the same object: >>> import sys >>> sys.getrefcount(1) 7...
>>> import sys >>> a = object() >>> sys.getrefcount(a) 2 >>> b = a >>> sys.getrefcount(a) 3 >>> del b >>> sys.getrefcount(a) 2
You can force deallocate objects even if their refcount isn't 0 in both Python 2 and 3. Both versions use the ctypes module to do so. WARNING: doing this will leave your Python environment unstable and prone to crashing without a traceback! Using this method could also introduce security problems ...
There are two approaches for influencing when a memory cleanup is performed. They are influencing how often the automatic process is performed and the other is manually triggering a cleanup. The garbage collector can be manipulated by tuning the collection thresholds which affect the frequency at w...
The fact that the garbage collection will clean up does not mean that you should wait for the garbage collection cycle to clean up. In particular you should not wait for garbage collection to close file handles, database connections and open network connections. for example: In the following code...

Page 1 of 1