Is there a way to delete created variables, functions, etc from the memory of the interpreter?












75















I've been searching for the accurate answer to this question for a couple of days now but haven't got anything good. I'm not a complete beginner in programming, but not yet even on the intermediate level.



When I'm in the shell of Python, I type: dir() and I can see all the names of all the objects in the current scope (main block), there are 6 of them:



['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']


Then, when I'm declaring a variable, for example x = 10, it automatically adds to that lists of objects under built-in module dir(), and when I type dir() again, it shows now:



['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x']


The same goes for functions, classes and so on.



How do I delete all those new objects without erasing the standard 6 which where available at the beginning?



I've read here about "memory cleaning", "cleaning of the console", which erases all the text from the command prompt window:



>>> import sys
>>> clear = lambda: os.system('cls')
>>> clear()


But all this has nothing to do with what I'm trying to achieve, it doesn't clean out all used objects.










share|improve this question




















  • 1





    Why do you feel you need to do this, or are you just asking out of curiosity?

    – PM 2Ring
    Oct 24 '14 at 10:05











  • I just didn't know that there is a del function out there. I'm beginning to learn Python and often have to experiment in the shell, so standard variable names like x or y are often already in use and restarting the shell takes another 15 sec to do (I have a very, very old laptop now). So I wanted to find a way to clean Python memory quicker.

    – funghorn
    Oct 24 '14 at 14:52











  • Ah. FWIW, del isn't exactly a function, hence no ( and ). It's a keyword which introduces a del statement. Of course, how it actually deletes an object may involve functions, but that's another story...

    – PM 2Ring
    Oct 25 '14 at 5:08











  • When experimenting in the shell names like x or y should not be in use unless you are using them. Or unless you do something silly like from _somemodule_ import *, then you'll get all sorts of garbage cluttering up the place. :)

    – PM 2Ring
    Oct 25 '14 at 5:08











  • Possible duplicate of How do I clear all variables in the middle of a Python script?

    – smac89
    Apr 23 '16 at 21:53
















75















I've been searching for the accurate answer to this question for a couple of days now but haven't got anything good. I'm not a complete beginner in programming, but not yet even on the intermediate level.



When I'm in the shell of Python, I type: dir() and I can see all the names of all the objects in the current scope (main block), there are 6 of them:



['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']


Then, when I'm declaring a variable, for example x = 10, it automatically adds to that lists of objects under built-in module dir(), and when I type dir() again, it shows now:



['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x']


The same goes for functions, classes and so on.



How do I delete all those new objects without erasing the standard 6 which where available at the beginning?



I've read here about "memory cleaning", "cleaning of the console", which erases all the text from the command prompt window:



>>> import sys
>>> clear = lambda: os.system('cls')
>>> clear()


But all this has nothing to do with what I'm trying to achieve, it doesn't clean out all used objects.










share|improve this question




















  • 1





    Why do you feel you need to do this, or are you just asking out of curiosity?

    – PM 2Ring
    Oct 24 '14 at 10:05











  • I just didn't know that there is a del function out there. I'm beginning to learn Python and often have to experiment in the shell, so standard variable names like x or y are often already in use and restarting the shell takes another 15 sec to do (I have a very, very old laptop now). So I wanted to find a way to clean Python memory quicker.

    – funghorn
    Oct 24 '14 at 14:52











  • Ah. FWIW, del isn't exactly a function, hence no ( and ). It's a keyword which introduces a del statement. Of course, how it actually deletes an object may involve functions, but that's another story...

    – PM 2Ring
    Oct 25 '14 at 5:08











  • When experimenting in the shell names like x or y should not be in use unless you are using them. Or unless you do something silly like from _somemodule_ import *, then you'll get all sorts of garbage cluttering up the place. :)

    – PM 2Ring
    Oct 25 '14 at 5:08











  • Possible duplicate of How do I clear all variables in the middle of a Python script?

    – smac89
    Apr 23 '16 at 21:53














75












75








75


24






I've been searching for the accurate answer to this question for a couple of days now but haven't got anything good. I'm not a complete beginner in programming, but not yet even on the intermediate level.



When I'm in the shell of Python, I type: dir() and I can see all the names of all the objects in the current scope (main block), there are 6 of them:



['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']


Then, when I'm declaring a variable, for example x = 10, it automatically adds to that lists of objects under built-in module dir(), and when I type dir() again, it shows now:



['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x']


The same goes for functions, classes and so on.



How do I delete all those new objects without erasing the standard 6 which where available at the beginning?



I've read here about "memory cleaning", "cleaning of the console", which erases all the text from the command prompt window:



>>> import sys
>>> clear = lambda: os.system('cls')
>>> clear()


But all this has nothing to do with what I'm trying to achieve, it doesn't clean out all used objects.










share|improve this question
















I've been searching for the accurate answer to this question for a couple of days now but haven't got anything good. I'm not a complete beginner in programming, but not yet even on the intermediate level.



When I'm in the shell of Python, I type: dir() and I can see all the names of all the objects in the current scope (main block), there are 6 of them:



['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']


Then, when I'm declaring a variable, for example x = 10, it automatically adds to that lists of objects under built-in module dir(), and when I type dir() again, it shows now:



['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x']


The same goes for functions, classes and so on.



How do I delete all those new objects without erasing the standard 6 which where available at the beginning?



I've read here about "memory cleaning", "cleaning of the console", which erases all the text from the command prompt window:



>>> import sys
>>> clear = lambda: os.system('cls')
>>> clear()


But all this has nothing to do with what I'm trying to achieve, it doesn't clean out all used objects.







python memory-management dir






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 25 '14 at 12:59









Unihedron

9,352104762




9,352104762










asked Oct 24 '14 at 9:20









funghornfunghorn

515169




515169








  • 1





    Why do you feel you need to do this, or are you just asking out of curiosity?

    – PM 2Ring
    Oct 24 '14 at 10:05











  • I just didn't know that there is a del function out there. I'm beginning to learn Python and often have to experiment in the shell, so standard variable names like x or y are often already in use and restarting the shell takes another 15 sec to do (I have a very, very old laptop now). So I wanted to find a way to clean Python memory quicker.

    – funghorn
    Oct 24 '14 at 14:52











  • Ah. FWIW, del isn't exactly a function, hence no ( and ). It's a keyword which introduces a del statement. Of course, how it actually deletes an object may involve functions, but that's another story...

    – PM 2Ring
    Oct 25 '14 at 5:08











  • When experimenting in the shell names like x or y should not be in use unless you are using them. Or unless you do something silly like from _somemodule_ import *, then you'll get all sorts of garbage cluttering up the place. :)

    – PM 2Ring
    Oct 25 '14 at 5:08











  • Possible duplicate of How do I clear all variables in the middle of a Python script?

    – smac89
    Apr 23 '16 at 21:53














  • 1





    Why do you feel you need to do this, or are you just asking out of curiosity?

    – PM 2Ring
    Oct 24 '14 at 10:05











  • I just didn't know that there is a del function out there. I'm beginning to learn Python and often have to experiment in the shell, so standard variable names like x or y are often already in use and restarting the shell takes another 15 sec to do (I have a very, very old laptop now). So I wanted to find a way to clean Python memory quicker.

    – funghorn
    Oct 24 '14 at 14:52











  • Ah. FWIW, del isn't exactly a function, hence no ( and ). It's a keyword which introduces a del statement. Of course, how it actually deletes an object may involve functions, but that's another story...

    – PM 2Ring
    Oct 25 '14 at 5:08











  • When experimenting in the shell names like x or y should not be in use unless you are using them. Or unless you do something silly like from _somemodule_ import *, then you'll get all sorts of garbage cluttering up the place. :)

    – PM 2Ring
    Oct 25 '14 at 5:08











  • Possible duplicate of How do I clear all variables in the middle of a Python script?

    – smac89
    Apr 23 '16 at 21:53








1




1





Why do you feel you need to do this, or are you just asking out of curiosity?

– PM 2Ring
Oct 24 '14 at 10:05





Why do you feel you need to do this, or are you just asking out of curiosity?

– PM 2Ring
Oct 24 '14 at 10:05













I just didn't know that there is a del function out there. I'm beginning to learn Python and often have to experiment in the shell, so standard variable names like x or y are often already in use and restarting the shell takes another 15 sec to do (I have a very, very old laptop now). So I wanted to find a way to clean Python memory quicker.

– funghorn
Oct 24 '14 at 14:52





I just didn't know that there is a del function out there. I'm beginning to learn Python and often have to experiment in the shell, so standard variable names like x or y are often already in use and restarting the shell takes another 15 sec to do (I have a very, very old laptop now). So I wanted to find a way to clean Python memory quicker.

– funghorn
Oct 24 '14 at 14:52













Ah. FWIW, del isn't exactly a function, hence no ( and ). It's a keyword which introduces a del statement. Of course, how it actually deletes an object may involve functions, but that's another story...

– PM 2Ring
Oct 25 '14 at 5:08





Ah. FWIW, del isn't exactly a function, hence no ( and ). It's a keyword which introduces a del statement. Of course, how it actually deletes an object may involve functions, but that's another story...

– PM 2Ring
Oct 25 '14 at 5:08













When experimenting in the shell names like x or y should not be in use unless you are using them. Or unless you do something silly like from _somemodule_ import *, then you'll get all sorts of garbage cluttering up the place. :)

– PM 2Ring
Oct 25 '14 at 5:08





When experimenting in the shell names like x or y should not be in use unless you are using them. Or unless you do something silly like from _somemodule_ import *, then you'll get all sorts of garbage cluttering up the place. :)

– PM 2Ring
Oct 25 '14 at 5:08













Possible duplicate of How do I clear all variables in the middle of a Python script?

– smac89
Apr 23 '16 at 21:53





Possible duplicate of How do I clear all variables in the middle of a Python script?

– smac89
Apr 23 '16 at 21:53












6 Answers
6






active

oldest

votes


















97














You can delete individual names with del:



del x


or you can remove them from the globals() object:



for name in dir():
if not name.startswith('_'):
del globals()[name]


This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.



Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.






share|improve this answer


























  • Well, I have to say startswith('_') seems quite naive. If someone is smart enough to write _foo=42 or even __foo__=42, how can we delete these? Is there a way to obtain standard module properties' names programmatically?

    – georg
    Oct 24 '14 at 9:29






  • 2





    @georg: I've coded the loop defensively. You'll have to hardcode an initial list of names to keep if you want to do better.

    – Martijn Pieters
    Oct 24 '14 at 9:29











  • So, no way? My thought was dir(ModuleType()), but it only returns doc and name.

    – georg
    Oct 24 '14 at 9:42






  • 1





    @georg: nope; the global namespace of the interpreter varies from release to release as well, and there is not foolproof way (that I know of) to enumerate what was in there when you opened the interpreter at a later stage.

    – Martijn Pieters
    Oct 24 '14 at 9:46











  • @georg: So if you really need to do this, just make a copy of the globals before you start adding stuff to the interpreter's name space. But why do you (or the OP) need to do this? If I have some large object I want gc'ed I usually just assign its name to something else, or occasionally I del it. And if the namespace gets too cluttered I simply kill the interpreter & restart it.

    – PM 2Ring
    Oct 24 '14 at 10:01



















38














Yes. There is a simple way to remove everything in iPython.
In iPython console, just type:



%reset


Then system will ask you to confirm. Press y.
If you don't want to see this prompt, simply type:



%reset -f


This should work..






share|improve this answer































    4














    If you are in an interactive environment like Jupyter or ipython you might be interested in clearing unwanted var's if they are getting heavy.



    The magic-commands reset and reset_selective is vailable on interactive python sessions like ipython and Jupyter



    1) reset




    reset Resets the namespace by removing all names defined by the user, if called without arguments.




    in and the out parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist parameter.



    reset in out


    Another interesting one is array that only removes numpy Arrays:



    reset array


    2) reset_selective




    Resets the namespace by removing names defined by the user.
    Input/Output history are left around in case you need them.




    Clean Array Example:



    In [1]: import numpy as np
    In [2]: littleArray = np.array([1,2,3,4,5])
    In [3]: who_ls
    Out[3]: ['littleArray', 'np']
    In [4]: reset_selective -f littleArray
    In [5]: who_ls
    Out[5]: ['np']


    Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html






    share|improve this answer

































      4














      You can use python garbage collector:



      import gc
      gc.collect()





      share|improve this answer



















      • 3





        Hey @Fardin! thanks! Your answer did the job and saved my day! But before gc.collect() I did del(variable).

        – Gmosy Gnaq
        Jul 31 '18 at 13:34





















      3














      Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name. You can also do it by assigning the variable to None



      a = 10
      print a

      del a
      print a ## throws an error here because it's been deleted already.


      The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del has no real effect, since those names would have been deleted as they went out of scope anyway.






      share|improve this answer


























      • Indeed. Of course, when working in the interpreter's global namespace names aren't going to go out of scope, but so what. :) I guess it's also worth mentioning that what happens to the memory used by objects that have been garbage collected is implementation-dependant, but in most Python implementations the gc'ed memory merely goes back to the Python pool, it's not returned to the OS until the program exits.

        – PM 2Ring
        Oct 24 '14 at 10:04











      • Yes! I forgot :P

        – d-coder
        Oct 24 '14 at 10:11






      • 2





        I guess your brain gc'ed that knowledge. :)

        – PM 2Ring
        Oct 24 '14 at 10:17






      • 2





        Note that in CPython the GC is only needed to break reference cycles. If no references remain, an object is insta-removed from memory. So del does have a real effect here.

        – Martijn Pieters
        Oct 24 '14 at 11:23








      • 2





        @eryksun: yes, as defined by RFC 4042-bis2, of course! :-P

        – Martijn Pieters
        Oct 24 '14 at 11:44



















      1














      This worked for me.



      You need to run it twice once for globals followed by locals



      for name in dir():
      if not name.startswith('_'):
      del globals()[name]

      for name in dir():
      if not name.startswith('_'):
      del locals()[name]





      share|improve this answer
























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26545051%2fis-there-a-way-to-delete-created-variables-functions-etc-from-the-memory-of-th%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        6 Answers
        6






        active

        oldest

        votes








        6 Answers
        6






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        97














        You can delete individual names with del:



        del x


        or you can remove them from the globals() object:



        for name in dir():
        if not name.startswith('_'):
        del globals()[name]


        This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.



        Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.






        share|improve this answer


























        • Well, I have to say startswith('_') seems quite naive. If someone is smart enough to write _foo=42 or even __foo__=42, how can we delete these? Is there a way to obtain standard module properties' names programmatically?

          – georg
          Oct 24 '14 at 9:29






        • 2





          @georg: I've coded the loop defensively. You'll have to hardcode an initial list of names to keep if you want to do better.

          – Martijn Pieters
          Oct 24 '14 at 9:29











        • So, no way? My thought was dir(ModuleType()), but it only returns doc and name.

          – georg
          Oct 24 '14 at 9:42






        • 1





          @georg: nope; the global namespace of the interpreter varies from release to release as well, and there is not foolproof way (that I know of) to enumerate what was in there when you opened the interpreter at a later stage.

          – Martijn Pieters
          Oct 24 '14 at 9:46











        • @georg: So if you really need to do this, just make a copy of the globals before you start adding stuff to the interpreter's name space. But why do you (or the OP) need to do this? If I have some large object I want gc'ed I usually just assign its name to something else, or occasionally I del it. And if the namespace gets too cluttered I simply kill the interpreter & restart it.

          – PM 2Ring
          Oct 24 '14 at 10:01
















        97














        You can delete individual names with del:



        del x


        or you can remove them from the globals() object:



        for name in dir():
        if not name.startswith('_'):
        del globals()[name]


        This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.



        Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.






        share|improve this answer


























        • Well, I have to say startswith('_') seems quite naive. If someone is smart enough to write _foo=42 or even __foo__=42, how can we delete these? Is there a way to obtain standard module properties' names programmatically?

          – georg
          Oct 24 '14 at 9:29






        • 2





          @georg: I've coded the loop defensively. You'll have to hardcode an initial list of names to keep if you want to do better.

          – Martijn Pieters
          Oct 24 '14 at 9:29











        • So, no way? My thought was dir(ModuleType()), but it only returns doc and name.

          – georg
          Oct 24 '14 at 9:42






        • 1





          @georg: nope; the global namespace of the interpreter varies from release to release as well, and there is not foolproof way (that I know of) to enumerate what was in there when you opened the interpreter at a later stage.

          – Martijn Pieters
          Oct 24 '14 at 9:46











        • @georg: So if you really need to do this, just make a copy of the globals before you start adding stuff to the interpreter's name space. But why do you (or the OP) need to do this? If I have some large object I want gc'ed I usually just assign its name to something else, or occasionally I del it. And if the namespace gets too cluttered I simply kill the interpreter & restart it.

          – PM 2Ring
          Oct 24 '14 at 10:01














        97












        97








        97







        You can delete individual names with del:



        del x


        or you can remove them from the globals() object:



        for name in dir():
        if not name.startswith('_'):
        del globals()[name]


        This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.



        Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.






        share|improve this answer















        You can delete individual names with del:



        del x


        or you can remove them from the globals() object:



        for name in dir():
        if not name.startswith('_'):
        del globals()[name]


        This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.



        Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Oct 25 '14 at 13:00









        Unihedron

        9,352104762




        9,352104762










        answered Oct 24 '14 at 9:24









        Martijn PietersMartijn Pieters

        723k14125372343




        723k14125372343













        • Well, I have to say startswith('_') seems quite naive. If someone is smart enough to write _foo=42 or even __foo__=42, how can we delete these? Is there a way to obtain standard module properties' names programmatically?

          – georg
          Oct 24 '14 at 9:29






        • 2





          @georg: I've coded the loop defensively. You'll have to hardcode an initial list of names to keep if you want to do better.

          – Martijn Pieters
          Oct 24 '14 at 9:29











        • So, no way? My thought was dir(ModuleType()), but it only returns doc and name.

          – georg
          Oct 24 '14 at 9:42






        • 1





          @georg: nope; the global namespace of the interpreter varies from release to release as well, and there is not foolproof way (that I know of) to enumerate what was in there when you opened the interpreter at a later stage.

          – Martijn Pieters
          Oct 24 '14 at 9:46











        • @georg: So if you really need to do this, just make a copy of the globals before you start adding stuff to the interpreter's name space. But why do you (or the OP) need to do this? If I have some large object I want gc'ed I usually just assign its name to something else, or occasionally I del it. And if the namespace gets too cluttered I simply kill the interpreter & restart it.

          – PM 2Ring
          Oct 24 '14 at 10:01



















        • Well, I have to say startswith('_') seems quite naive. If someone is smart enough to write _foo=42 or even __foo__=42, how can we delete these? Is there a way to obtain standard module properties' names programmatically?

          – georg
          Oct 24 '14 at 9:29






        • 2





          @georg: I've coded the loop defensively. You'll have to hardcode an initial list of names to keep if you want to do better.

          – Martijn Pieters
          Oct 24 '14 at 9:29











        • So, no way? My thought was dir(ModuleType()), but it only returns doc and name.

          – georg
          Oct 24 '14 at 9:42






        • 1





          @georg: nope; the global namespace of the interpreter varies from release to release as well, and there is not foolproof way (that I know of) to enumerate what was in there when you opened the interpreter at a later stage.

          – Martijn Pieters
          Oct 24 '14 at 9:46











        • @georg: So if you really need to do this, just make a copy of the globals before you start adding stuff to the interpreter's name space. But why do you (or the OP) need to do this? If I have some large object I want gc'ed I usually just assign its name to something else, or occasionally I del it. And if the namespace gets too cluttered I simply kill the interpreter & restart it.

          – PM 2Ring
          Oct 24 '14 at 10:01

















        Well, I have to say startswith('_') seems quite naive. If someone is smart enough to write _foo=42 or even __foo__=42, how can we delete these? Is there a way to obtain standard module properties' names programmatically?

        – georg
        Oct 24 '14 at 9:29





        Well, I have to say startswith('_') seems quite naive. If someone is smart enough to write _foo=42 or even __foo__=42, how can we delete these? Is there a way to obtain standard module properties' names programmatically?

        – georg
        Oct 24 '14 at 9:29




        2




        2





        @georg: I've coded the loop defensively. You'll have to hardcode an initial list of names to keep if you want to do better.

        – Martijn Pieters
        Oct 24 '14 at 9:29





        @georg: I've coded the loop defensively. You'll have to hardcode an initial list of names to keep if you want to do better.

        – Martijn Pieters
        Oct 24 '14 at 9:29













        So, no way? My thought was dir(ModuleType()), but it only returns doc and name.

        – georg
        Oct 24 '14 at 9:42





        So, no way? My thought was dir(ModuleType()), but it only returns doc and name.

        – georg
        Oct 24 '14 at 9:42




        1




        1





        @georg: nope; the global namespace of the interpreter varies from release to release as well, and there is not foolproof way (that I know of) to enumerate what was in there when you opened the interpreter at a later stage.

        – Martijn Pieters
        Oct 24 '14 at 9:46





        @georg: nope; the global namespace of the interpreter varies from release to release as well, and there is not foolproof way (that I know of) to enumerate what was in there when you opened the interpreter at a later stage.

        – Martijn Pieters
        Oct 24 '14 at 9:46













        @georg: So if you really need to do this, just make a copy of the globals before you start adding stuff to the interpreter's name space. But why do you (or the OP) need to do this? If I have some large object I want gc'ed I usually just assign its name to something else, or occasionally I del it. And if the namespace gets too cluttered I simply kill the interpreter & restart it.

        – PM 2Ring
        Oct 24 '14 at 10:01





        @georg: So if you really need to do this, just make a copy of the globals before you start adding stuff to the interpreter's name space. But why do you (or the OP) need to do this? If I have some large object I want gc'ed I usually just assign its name to something else, or occasionally I del it. And if the namespace gets too cluttered I simply kill the interpreter & restart it.

        – PM 2Ring
        Oct 24 '14 at 10:01













        38














        Yes. There is a simple way to remove everything in iPython.
        In iPython console, just type:



        %reset


        Then system will ask you to confirm. Press y.
        If you don't want to see this prompt, simply type:



        %reset -f


        This should work..






        share|improve this answer




























          38














          Yes. There is a simple way to remove everything in iPython.
          In iPython console, just type:



          %reset


          Then system will ask you to confirm. Press y.
          If you don't want to see this prompt, simply type:



          %reset -f


          This should work..






          share|improve this answer


























            38












            38








            38







            Yes. There is a simple way to remove everything in iPython.
            In iPython console, just type:



            %reset


            Then system will ask you to confirm. Press y.
            If you don't want to see this prompt, simply type:



            %reset -f


            This should work..






            share|improve this answer













            Yes. There is a simple way to remove everything in iPython.
            In iPython console, just type:



            %reset


            Then system will ask you to confirm. Press y.
            If you don't want to see this prompt, simply type:



            %reset -f


            This should work..







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 13 '16 at 12:58









            EyesBearEyesBear

            48143




            48143























                4














                If you are in an interactive environment like Jupyter or ipython you might be interested in clearing unwanted var's if they are getting heavy.



                The magic-commands reset and reset_selective is vailable on interactive python sessions like ipython and Jupyter



                1) reset




                reset Resets the namespace by removing all names defined by the user, if called without arguments.




                in and the out parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist parameter.



                reset in out


                Another interesting one is array that only removes numpy Arrays:



                reset array


                2) reset_selective




                Resets the namespace by removing names defined by the user.
                Input/Output history are left around in case you need them.




                Clean Array Example:



                In [1]: import numpy as np
                In [2]: littleArray = np.array([1,2,3,4,5])
                In [3]: who_ls
                Out[3]: ['littleArray', 'np']
                In [4]: reset_selective -f littleArray
                In [5]: who_ls
                Out[5]: ['np']


                Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html






                share|improve this answer






























                  4














                  If you are in an interactive environment like Jupyter or ipython you might be interested in clearing unwanted var's if they are getting heavy.



                  The magic-commands reset and reset_selective is vailable on interactive python sessions like ipython and Jupyter



                  1) reset




                  reset Resets the namespace by removing all names defined by the user, if called without arguments.




                  in and the out parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist parameter.



                  reset in out


                  Another interesting one is array that only removes numpy Arrays:



                  reset array


                  2) reset_selective




                  Resets the namespace by removing names defined by the user.
                  Input/Output history are left around in case you need them.




                  Clean Array Example:



                  In [1]: import numpy as np
                  In [2]: littleArray = np.array([1,2,3,4,5])
                  In [3]: who_ls
                  Out[3]: ['littleArray', 'np']
                  In [4]: reset_selective -f littleArray
                  In [5]: who_ls
                  Out[5]: ['np']


                  Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html






                  share|improve this answer




























                    4












                    4








                    4







                    If you are in an interactive environment like Jupyter or ipython you might be interested in clearing unwanted var's if they are getting heavy.



                    The magic-commands reset and reset_selective is vailable on interactive python sessions like ipython and Jupyter



                    1) reset




                    reset Resets the namespace by removing all names defined by the user, if called without arguments.




                    in and the out parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist parameter.



                    reset in out


                    Another interesting one is array that only removes numpy Arrays:



                    reset array


                    2) reset_selective




                    Resets the namespace by removing names defined by the user.
                    Input/Output history are left around in case you need them.




                    Clean Array Example:



                    In [1]: import numpy as np
                    In [2]: littleArray = np.array([1,2,3,4,5])
                    In [3]: who_ls
                    Out[3]: ['littleArray', 'np']
                    In [4]: reset_selective -f littleArray
                    In [5]: who_ls
                    Out[5]: ['np']


                    Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html






                    share|improve this answer















                    If you are in an interactive environment like Jupyter or ipython you might be interested in clearing unwanted var's if they are getting heavy.



                    The magic-commands reset and reset_selective is vailable on interactive python sessions like ipython and Jupyter



                    1) reset




                    reset Resets the namespace by removing all names defined by the user, if called without arguments.




                    in and the out parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist parameter.



                    reset in out


                    Another interesting one is array that only removes numpy Arrays:



                    reset array


                    2) reset_selective




                    Resets the namespace by removing names defined by the user.
                    Input/Output history are left around in case you need them.




                    Clean Array Example:



                    In [1]: import numpy as np
                    In [2]: littleArray = np.array([1,2,3,4,5])
                    In [3]: who_ls
                    Out[3]: ['littleArray', 'np']
                    In [4]: reset_selective -f littleArray
                    In [5]: who_ls
                    Out[5]: ['np']


                    Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 11 '17 at 20:14

























                    answered Dec 11 '17 at 19:53









                    user1767754user1767754

                    10.2k57385




                    10.2k57385























                        4














                        You can use python garbage collector:



                        import gc
                        gc.collect()





                        share|improve this answer



















                        • 3





                          Hey @Fardin! thanks! Your answer did the job and saved my day! But before gc.collect() I did del(variable).

                          – Gmosy Gnaq
                          Jul 31 '18 at 13:34


















                        4














                        You can use python garbage collector:



                        import gc
                        gc.collect()





                        share|improve this answer



















                        • 3





                          Hey @Fardin! thanks! Your answer did the job and saved my day! But before gc.collect() I did del(variable).

                          – Gmosy Gnaq
                          Jul 31 '18 at 13:34
















                        4












                        4








                        4







                        You can use python garbage collector:



                        import gc
                        gc.collect()





                        share|improve this answer













                        You can use python garbage collector:



                        import gc
                        gc.collect()






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Mar 28 '18 at 22:01









                        FardinFardin

                        361412




                        361412








                        • 3





                          Hey @Fardin! thanks! Your answer did the job and saved my day! But before gc.collect() I did del(variable).

                          – Gmosy Gnaq
                          Jul 31 '18 at 13:34
















                        • 3





                          Hey @Fardin! thanks! Your answer did the job and saved my day! But before gc.collect() I did del(variable).

                          – Gmosy Gnaq
                          Jul 31 '18 at 13:34










                        3




                        3





                        Hey @Fardin! thanks! Your answer did the job and saved my day! But before gc.collect() I did del(variable).

                        – Gmosy Gnaq
                        Jul 31 '18 at 13:34







                        Hey @Fardin! thanks! Your answer did the job and saved my day! But before gc.collect() I did del(variable).

                        – Gmosy Gnaq
                        Jul 31 '18 at 13:34













                        3














                        Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name. You can also do it by assigning the variable to None



                        a = 10
                        print a

                        del a
                        print a ## throws an error here because it's been deleted already.


                        The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del has no real effect, since those names would have been deleted as they went out of scope anyway.






                        share|improve this answer


























                        • Indeed. Of course, when working in the interpreter's global namespace names aren't going to go out of scope, but so what. :) I guess it's also worth mentioning that what happens to the memory used by objects that have been garbage collected is implementation-dependant, but in most Python implementations the gc'ed memory merely goes back to the Python pool, it's not returned to the OS until the program exits.

                          – PM 2Ring
                          Oct 24 '14 at 10:04











                        • Yes! I forgot :P

                          – d-coder
                          Oct 24 '14 at 10:11






                        • 2





                          I guess your brain gc'ed that knowledge. :)

                          – PM 2Ring
                          Oct 24 '14 at 10:17






                        • 2





                          Note that in CPython the GC is only needed to break reference cycles. If no references remain, an object is insta-removed from memory. So del does have a real effect here.

                          – Martijn Pieters
                          Oct 24 '14 at 11:23








                        • 2





                          @eryksun: yes, as defined by RFC 4042-bis2, of course! :-P

                          – Martijn Pieters
                          Oct 24 '14 at 11:44
















                        3














                        Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name. You can also do it by assigning the variable to None



                        a = 10
                        print a

                        del a
                        print a ## throws an error here because it's been deleted already.


                        The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del has no real effect, since those names would have been deleted as they went out of scope anyway.






                        share|improve this answer


























                        • Indeed. Of course, when working in the interpreter's global namespace names aren't going to go out of scope, but so what. :) I guess it's also worth mentioning that what happens to the memory used by objects that have been garbage collected is implementation-dependant, but in most Python implementations the gc'ed memory merely goes back to the Python pool, it's not returned to the OS until the program exits.

                          – PM 2Ring
                          Oct 24 '14 at 10:04











                        • Yes! I forgot :P

                          – d-coder
                          Oct 24 '14 at 10:11






                        • 2





                          I guess your brain gc'ed that knowledge. :)

                          – PM 2Ring
                          Oct 24 '14 at 10:17






                        • 2





                          Note that in CPython the GC is only needed to break reference cycles. If no references remain, an object is insta-removed from memory. So del does have a real effect here.

                          – Martijn Pieters
                          Oct 24 '14 at 11:23








                        • 2





                          @eryksun: yes, as defined by RFC 4042-bis2, of course! :-P

                          – Martijn Pieters
                          Oct 24 '14 at 11:44














                        3












                        3








                        3







                        Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name. You can also do it by assigning the variable to None



                        a = 10
                        print a

                        del a
                        print a ## throws an error here because it's been deleted already.


                        The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del has no real effect, since those names would have been deleted as they went out of scope anyway.






                        share|improve this answer















                        Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name. You can also do it by assigning the variable to None



                        a = 10
                        print a

                        del a
                        print a ## throws an error here because it's been deleted already.


                        The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del has no real effect, since those names would have been deleted as they went out of scope anyway.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Oct 25 '14 at 13:01









                        Unihedron

                        9,352104762




                        9,352104762










                        answered Oct 24 '14 at 9:41









                        d-coderd-coder

                        3,84121226




                        3,84121226













                        • Indeed. Of course, when working in the interpreter's global namespace names aren't going to go out of scope, but so what. :) I guess it's also worth mentioning that what happens to the memory used by objects that have been garbage collected is implementation-dependant, but in most Python implementations the gc'ed memory merely goes back to the Python pool, it's not returned to the OS until the program exits.

                          – PM 2Ring
                          Oct 24 '14 at 10:04











                        • Yes! I forgot :P

                          – d-coder
                          Oct 24 '14 at 10:11






                        • 2





                          I guess your brain gc'ed that knowledge. :)

                          – PM 2Ring
                          Oct 24 '14 at 10:17






                        • 2





                          Note that in CPython the GC is only needed to break reference cycles. If no references remain, an object is insta-removed from memory. So del does have a real effect here.

                          – Martijn Pieters
                          Oct 24 '14 at 11:23








                        • 2





                          @eryksun: yes, as defined by RFC 4042-bis2, of course! :-P

                          – Martijn Pieters
                          Oct 24 '14 at 11:44



















                        • Indeed. Of course, when working in the interpreter's global namespace names aren't going to go out of scope, but so what. :) I guess it's also worth mentioning that what happens to the memory used by objects that have been garbage collected is implementation-dependant, but in most Python implementations the gc'ed memory merely goes back to the Python pool, it's not returned to the OS until the program exits.

                          – PM 2Ring
                          Oct 24 '14 at 10:04











                        • Yes! I forgot :P

                          – d-coder
                          Oct 24 '14 at 10:11






                        • 2





                          I guess your brain gc'ed that knowledge. :)

                          – PM 2Ring
                          Oct 24 '14 at 10:17






                        • 2





                          Note that in CPython the GC is only needed to break reference cycles. If no references remain, an object is insta-removed from memory. So del does have a real effect here.

                          – Martijn Pieters
                          Oct 24 '14 at 11:23








                        • 2





                          @eryksun: yes, as defined by RFC 4042-bis2, of course! :-P

                          – Martijn Pieters
                          Oct 24 '14 at 11:44

















                        Indeed. Of course, when working in the interpreter's global namespace names aren't going to go out of scope, but so what. :) I guess it's also worth mentioning that what happens to the memory used by objects that have been garbage collected is implementation-dependant, but in most Python implementations the gc'ed memory merely goes back to the Python pool, it's not returned to the OS until the program exits.

                        – PM 2Ring
                        Oct 24 '14 at 10:04





                        Indeed. Of course, when working in the interpreter's global namespace names aren't going to go out of scope, but so what. :) I guess it's also worth mentioning that what happens to the memory used by objects that have been garbage collected is implementation-dependant, but in most Python implementations the gc'ed memory merely goes back to the Python pool, it's not returned to the OS until the program exits.

                        – PM 2Ring
                        Oct 24 '14 at 10:04













                        Yes! I forgot :P

                        – d-coder
                        Oct 24 '14 at 10:11





                        Yes! I forgot :P

                        – d-coder
                        Oct 24 '14 at 10:11




                        2




                        2





                        I guess your brain gc'ed that knowledge. :)

                        – PM 2Ring
                        Oct 24 '14 at 10:17





                        I guess your brain gc'ed that knowledge. :)

                        – PM 2Ring
                        Oct 24 '14 at 10:17




                        2




                        2





                        Note that in CPython the GC is only needed to break reference cycles. If no references remain, an object is insta-removed from memory. So del does have a real effect here.

                        – Martijn Pieters
                        Oct 24 '14 at 11:23







                        Note that in CPython the GC is only needed to break reference cycles. If no references remain, an object is insta-removed from memory. So del does have a real effect here.

                        – Martijn Pieters
                        Oct 24 '14 at 11:23






                        2




                        2





                        @eryksun: yes, as defined by RFC 4042-bis2, of course! :-P

                        – Martijn Pieters
                        Oct 24 '14 at 11:44





                        @eryksun: yes, as defined by RFC 4042-bis2, of course! :-P

                        – Martijn Pieters
                        Oct 24 '14 at 11:44











                        1














                        This worked for me.



                        You need to run it twice once for globals followed by locals



                        for name in dir():
                        if not name.startswith('_'):
                        del globals()[name]

                        for name in dir():
                        if not name.startswith('_'):
                        del locals()[name]





                        share|improve this answer




























                          1














                          This worked for me.



                          You need to run it twice once for globals followed by locals



                          for name in dir():
                          if not name.startswith('_'):
                          del globals()[name]

                          for name in dir():
                          if not name.startswith('_'):
                          del locals()[name]





                          share|improve this answer


























                            1












                            1








                            1







                            This worked for me.



                            You need to run it twice once for globals followed by locals



                            for name in dir():
                            if not name.startswith('_'):
                            del globals()[name]

                            for name in dir():
                            if not name.startswith('_'):
                            del locals()[name]





                            share|improve this answer













                            This worked for me.



                            You need to run it twice once for globals followed by locals



                            for name in dir():
                            if not name.startswith('_'):
                            del globals()[name]

                            for name in dir():
                            if not name.startswith('_'):
                            del locals()[name]






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 21 '18 at 15:40









                            ViswaViswa

                            111




                            111






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f26545051%2fis-there-a-way-to-delete-created-variables-functions-etc-from-the-memory-of-th%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                鏡平學校

                                ꓛꓣだゔៀៅຸ໢ທຮ໕໒ ,ໂ'໥໓າ໼ឨឲ៵៭ៈゎゔit''䖳𥁄卿' ☨₤₨こゎもょの;ꜹꟚꞖꞵꟅꞛေၦေɯ,ɨɡ𛃵𛁹ޝ޳ޠ޾,ޤޒޯ޾𫝒𫠁သ𛅤チョ'サノބޘދ𛁐ᶿᶇᶀᶋᶠ㨑㽹⻮ꧬ꧹؍۩وَؠ㇕㇃㇪ ㇦㇋㇋ṜẰᵡᴠ 軌ᵕ搜۳ٰޗޮ޷ސޯ𫖾𫅀ल, ꙭ꙰ꚅꙁꚊꞻꝔ꟠Ꝭㄤﺟޱސꧨꧼ꧴ꧯꧽ꧲ꧯ'⽹⽭⾁⿞⼳⽋២៩ញណើꩯꩤ꩸ꩮᶻᶺᶧᶂ𫳲𫪭𬸄𫵰𬖩𬫣𬊉ၲ𛅬㕦䬺𫝌𫝼,,𫟖𫞽ហៅ஫㆔ాఆఅꙒꚞꙍ,Ꙟ꙱エ ,ポテ,フࢰࢯ𫟠𫞶 𫝤𫟠ﺕﹱﻜﻣ𪵕𪭸𪻆𪾩𫔷ġ,ŧآꞪ꟥,ꞔꝻ♚☹⛵𛀌ꬷꭞȄƁƪƬșƦǙǗdžƝǯǧⱦⱰꓕꓢႋ神 ဴ၀க௭எ௫ឫោ ' េㇷㇴㇼ神ㇸㇲㇽㇴㇼㇻㇸ'ㇸㇿㇸㇹㇰㆣꓚꓤ₡₧ ㄨㄟ㄂ㄖㄎ໗ツڒذ₶।ऩछएोञयूटक़कयँृी,冬'𛅢𛅥ㇱㇵㇶ𥄥𦒽𠣧𠊓𧢖𥞘𩔋цѰㄠſtʯʭɿʆʗʍʩɷɛ,əʏダヵㄐㄘR{gỚṖḺờṠṫảḙḭᴮᵏᴘᵀᵷᵕᴜᴏᵾq﮲ﲿﴽﭙ軌ﰬﶚﶧ﫲Ҝжюїкӈㇴffצּ﬘﭅﬈軌'ffistfflſtffतभफɳɰʊɲʎ𛁱𛁖𛁮𛀉 𛂯𛀞నఋŀŲ 𫟲𫠖𫞺ຆຆ ໹້໕໗ๆทԊꧢꧠ꧰ꓱ⿝⼑ŎḬẃẖỐẅ ,ờỰỈỗﮊDžȩꭏꭎꬻ꭮ꬿꭖꭥꭅ㇭神 ⾈ꓵꓑ⺄㄄ㄪㄙㄅㄇstA۵䞽ॶ𫞑𫝄㇉㇇゜軌𩜛𩳠Jﻺ‚Üမ႕ႌႊၐၸဓၞၞၡ៸wyvtᶎᶪᶹစဎ꣡꣰꣢꣤ٗ؋لㇳㇾㇻㇱ㆐㆔,,㆟Ⱶヤマފ޼ޝަݿݞݠݷݐ',ݘ,ݪݙݵ𬝉𬜁𫝨𫞘くせぉて¼óû×ó£…𛅑הㄙくԗԀ5606神45,神796'𪤻𫞧ꓐ㄁ㄘɥɺꓵꓲ3''7034׉ⱦⱠˆ“𫝋ȍ,ꩲ軌꩷ꩶꩧꩫఞ۔فڱێظペサ神ナᴦᵑ47 9238їﻂ䐊䔉㠸﬎ffiﬣ,לּᴷᴦᵛᵽ,ᴨᵤ ᵸᵥᴗᵈꚏꚉꚟ⻆rtǟƴ𬎎

                                Why https connections are so slow when debugging (stepping over) in Java?