If I create a list in a python function and return it to the caller, how does garbage collection work on that list? Do I have to do anything to keep a memory leak from occurring?
For example:
#!/usr/bin/python
import random
class Example:
def f1(self):
list = []
len = random.randint(0, 30)
for i in range (0, len):
list.append(random.randint(0, 65536))
return list
random.seed(None)
e = Example()
while (1):
l = e.f1()
Will this cause a memory leak? Does the ‘list’ in f1() have an appropriate reference count at all times? Does the caller of f1() have to do anything to keep a memory leak from occurring? Should the caller do a del() on the list or something?
There’s no memory leak here. The list assigned to
lis the same list that is generated in the function. Python passes objects, not references or values.Python keeps track of the references to that list: on each iteration of the
whileloop, a new list is created and assigned tol. This causes the previous one to no longer have any references, so it will be deleted.