Reputation: 539
If I create an instance of a class without assigning it to a variable will it occupy memory every time I run the code? Or does the memory free up after the line of code containing the instance is executed?
For example:
class TestClass():
def __init__(self):
self.Moto = "Moto"
def printIt(self):
print self.Moto
So if I use it like this:
TestClass().printIt()
Does it occupy more and more memory every time the line is executed?
Upvotes: 5
Views: 2802
Reputation: 101929
No, the object will be garbage collected immediately, even though when the garbage collector "kicks in" and actually free the object is implementation dependent.
If we look at the CPython source code, we can see that the object is deallocated immediately:
/* Include/object.h */
#define Py_DECREF(op) \
do { \
if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \
--((PyObject*)(op))->ob_refcnt != 0) \
_Py_CHECK_REFCNT(op) \
else \
_Py_Dealloc((PyObject *)(op)); \
} while (0)
And _Py_Dealloc
is defined as:
#define _Py_Dealloc(op) ( \
_Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \
(*Py_TYPE(op)->tp_dealloc)((PyObject *)(op)))
#endif /* !Py_TRACE_REFS */
So as you can see The tp_dealloc
slot, which has the responsibility to free the memory is called directly.
Other implementations, like PyPy, IronPython or Jython may not free the memory immediatly, this could lead to a termporary increase in the memory usage.
In particular I believe in Jython everything depends on the Java garbage collector, which is not guaranteed to free the memory as soon as it can. Even calling System.gc()
is a mere suggestion for the garbage collector but it does not force it to free the memory.
Upvotes: 2
Reputation: 500307
No, the instance will be automatically garbage collected. The exact mechanism depends on the Python implementation. CPython uses reference counting and will free the instance at the end of TestClass().printIt()
.
If, however, you were to retain one or more references to the newly constructed object, the object would be kept alive for as long as it's being referenced.
Upvotes: 5