Variables & Garbage Collection
Variables in Python– by Sagar Jaybhay
In memory of computer memory address have these locations and value is stored in that location. The variable name is a reference to that object in that memory location (on that address).
Python is a dynamically typed language.
In python, we can find out memory address referenced by a variable by use of id( ) function.
In the above example when we declared i=10 then python will create an object of type int and assign 10 value to this object and stored on some memory location ex. 0x001223. So in this, I is like a pointer to object which point to a memory address.
Reference Counting: This is done by Python Memory manager and it counts the actual number of the object which holds or point that memory location.
Reference Counting: This is done by Python Memory manager and it counts the actual number of object which hold or point that memory location.
I= [1, 2, 3]; J=I; sys.getrefcount(I)
Reference count is 2. Because it point to that memory location.
By using this you get the count but when you pass variable to function it will create another object reference and the count is increased by 1. Means it create the extra reference. The answer to the above code is 3. For this, you need to import the sys module.
ctypes is a foreign function library for Python. It provides C compatible data types and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.
Python memory manager check the reference count which object holds. If that count goes to 0 then python program manager reclaims that memory by destroying that object. But sometimes it is not working.
Circular references: A=B , B=A
You can control the garbage collection programmatically by using gc module.
By default is it is turned on. You can turn off, it might have performance reason to turn off but you need to sure about your program doesn’t create circular references and memory leaks never happened. It runs periodically. Also you can clean up your code. If you have created destructor in class then garbage collector not handle this.
Dynamic vs static typing
Languages like c#, java are statically typed language. In this language when you want to declare a variable or initialized that variable you need to give data type and then assign value and this is done at compile time only so it is statically typed languages.
Python is dynamically type language when we initialize value there is no need to set the data type for that variable it just a reference.
Reassignment of value: when you assign value i=10; it created in memory and reference point that memory location i. when you again assign i=20 then it does not override value 10 to 20 rather than it creates a new object in memory and assigns a new reference to that i.