Skip to content

Variables in Python


variables are memory references, not equal to the object but reference(alias) the object at memory space.

Find out memory address referenced: using id()

reference counting

after we created a object in memory, python keep track of the number of the references we have to the object, as soon as the count goes to 0, python memory manager destroy object and reclaim the memory space

Find out reference count:

  • using sys.getrefcount()
  • using ctypes.c_long.from_address()

circular references

in the circumstance of circular reference, the reference count could not goes to 0(memory leak), need garbage collector to identify it

garbage collection

can be control programmatically using the gc module, turned on by default, beware to turn it off, for python < 3.4, if even one of the objects in the circular reference has a destructor, the destruction order may be important, but the GC does not know what order should be, so the circular reference objects will be marked as uncollectable and cause memory leak

dynamically typing

python variable name has no references to any type, when we use type(), python looks up the object which is referenced and return the type of the object

variable equality

  • identity operator(var_a is var_b) compare the memory address
  • equality operator(var_a == var_b) compare the object state


發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *