Deleting variables after finishing executing a function

This is the place for queries that don't fit in any of the other categories.

Deleting variables after finishing executing a function

Postby raafat » Thu Nov 14, 2013 11:03 am

Hi there...i'm wondering if should i delete each varaible i used in my function or my class after finishing executing a function ?

Assuming i have this function

Code: Select all
def blah():
    vari1 = somevalue
    vari2 = somevalue
 
    dosomething..
    the end of function

What about vari1,vari2 ? should i delete them or will Python do so ?

thank you.
Last edited by Mekire on Thu Nov 14, 2013 11:07 am, edited 1 time in total.
Reason: First post lock. Code tags added.
raafat
 
Posts: 2
Joined: Thu Nov 14, 2013 10:52 am

Re: Deleting variables after finishing executing a function

Postby Mekire » Thu Nov 14, 2013 11:10 am

Python has what is called a garbage collector. As soon as a variable goes out of scope in a function, or there are no remaining references to an object, the memory is reclaimed. It is very, very uncommon to actually need to delete an object manually.

-Mek
User avatar
Mekire
 
Posts: 986
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: Deleting variables after finishing executing a function

Postby micseydel » Thu Nov 14, 2013 7:02 pm

Mekire wrote:As soon as a variable goes out of scope in a function, or there are no remaining references to an object, the memory is reclaimed.

Actually, Python won't necessarily garbage collect it right away. It will definitely do so if it needs memory but you don't actually know when that will happen.

raafat wrote:What about vari1,vari2 ? should i delete them or will Python do so ?

As Mekire said, Python will do it for you, but just as added incentive for you to not do it yourself, if you use the del keyword it's much like the variable going out of scope, it can be garbage collected but you don't know that it will be.

Do note though that even if you did need to delete a variable before it goes out of scope, realize that doing so on large data structures is the only time it makes sense. You wouldn't do it to an int or anything.
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1223
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Deleting variables after finishing executing a function

Postby raafat » Sat Nov 23, 2013 11:39 am

So Python will do it...thank you guys
raafat
 
Posts: 2
Joined: Thu Nov 14, 2013 10:52 am


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests