Reputation: 1
How does Python manages memory allocated to function variables when a function like groupby_even_odd
shown below is called?
What happens to memory used by function variables even_nums/odd_nums
after the values are returned?
My search has yield information that is a little too technical for me to digest. If anyone can point me out to some good info or share some pointers I would greatly appreciate it.
Thanks in advance.
def groupby_even_odd(numbers):
even_nums = [number for number in numbers if not number % 2]
odd_nums = [number for number in numbers if number % 2]
return {'even': even_nums, 'odd': odd_nums}
Upvotes: 0
Views: 204
Reputation: 309891
CPython's memory management is based on reference counting. Basically, it keeps track of how many "things" in the code are referencing a particular object. When the reference count drops to 0, the object's memory is reclaimed by python for re-use or possibly deallocated entirely. As an example:
even_nums
, that list has a reference count of 1 (even_nums
refers to that list).even_nums
so the reference count goes to 2.even_nums
) goes away which makes the reference count drop back to 1.At this point, we can't say much else. If the caller then keeps a reference to the return value, then the reference count will stay at 1. If the caller does not keep a reference to the return value, the reference count will drop to 0 and the garbage collector will reclaim that memory.
There are also some subtleties that can arise with cyclic references (a list refers to an object that refers back to the list). In this case, there is no way that the reference count could ever drop to 0 on it's own. Fortunately, python detects these circumstances and is able to free those objects to prevent memory leaks.
Upvotes: 1