Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a variable released from memory? [duplicate]

Tags:

python

memory

Say I define a function, which builds a list, and then prints the items of the list one by one (no practical use, just an example:

import os

def build_and_print():
    thingy = os.walk('some directory')
    for i in thingy:
        print i

if __name__ == '__main__:
    build_and_print()

If the thingy that is built is very large it could take up a lot of memory, at what point will it be released from memory?

Does python store the variable thingy until the script is finished running or until the function that builds/uses it is finished running?

like image 937
Joe Smart Avatar asked Feb 14 '26 09:02

Joe Smart


1 Answers

Once a Variable goes out of scope, it is collected by the garbage collector.

You can see the collector code here. Go to collect function, there comments explain the process well.

like image 148
Navneet Avatar answered Feb 16 '26 22:02

Navneet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!