Import module vs garbage collector | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Import module vs garbage collector

Will garbage collector clear module imported within an object after it's deleted?

26th Jan 2019, 1:50 PM
D F
1 Answer
+ 6
There is an algorithm called reference counting that python employs. If reference counting field reaches zero, CPython automatically calls the object-specific deallocation function. If an object contains references to other objects, then their reference count is decremented too. Thus other objects may be deallocated in turn. Variables, which are declared outside of functions, classes, and blocks are called globals. Usually, such variables live until the end of the Python's process. Thus, the reference count of objects, which are referred by global variables, never drops to 0. Variable, which are defined inside blocks (e.g., in a function or class) have a local scope (i.e., they are local to its block). If Python interpreter exits from the block, it destroys all references created inside the block. You can always check the number of current references using sys.getrefcount function. Note: modules are just collection of objects as everything in python is an object
27th Jan 2019, 2:28 AM
Dan Rhamba
Dan Rhamba - avatar