Reputation: 448
Say there is
class thing(object):
def __init__(self):
self.text = "foo"
def bar():
obj = thing()
#do something with the object
bar()
Is obj deleted from memory after bar() finishes, or is it still in memory, just can't be accessed since it is a local variable of bar? (This assumes obj is not put into a global or external container such as a dictionary or list, of course).
Upvotes: 17
Views: 8080
Reputation: 1125388
The object obj
references will be deleted when the function exits.
That's because CPython (the default Python implementation) uses reference counting to track object lifetimes. obj
is a local variable and only exists for the duration of the function. thing()
is an instance with just one reference, obj
, and when obj
is cleaned up, the reference count drops to 0 and thing()
is immediately deleted.
If you are using PyPy, IronPython, Jython or some other implementation, object destruction can be delayed as implementations are free to use different garbage collection schemes. This is only important for implementing a __del__
method, as their invocation can be delayed.
I recommend you read the excellent Facts and myths about Python names and values if you want to know more about how Python names work.
Upvotes: 19
Reputation: 6994
Incorporating corrections:
Yes, objects with a reference count of 0 are reclaimed when a function goes out of scope.
Python has builtins, global (module) scope and function scope.
If you have a resource that needs to get freed as soon as the scope exits, put it in a with
block and put the logic to free the resource in __exit__
. The variable associated with the with
block is still local to the enclosing function or module.
The idiom for resources that should be freed as soon as they go out of scope is with
, e.g.
with open("frodo.txt","r") as fh:
for line in fh:
do_something(line)
In CPython, prior to version 3.4, objects with a custom __del__
method might be deleted in a non-deterministic order if they are involved in a cycle.
Upvotes: -2