creanion
creanion

Reputation: 2743

How to cleanup jupyter's background variables?

How do I remove all Jupyter's - Python3 kernel - background variables that keep extra references to intermediate values in the execution? Specifically, without restarting the kernel.

The intention is to save memory - to not hang on to references of variables that have already been deleted or overwritten after filtering data.

I've come up with this to remove some background variables:

import re

def cleanup_nb_names():
    for name in list(globals()):
        if re.match(r"(_i\d+|_\d+|_+)$", name):
            globals().pop(name)
        if name in ('In', 'Out'):
            globals()[name].clear()

cleanup_nb_names()

The thinking is to:

Is there a better way to do this? Is something missing?

Upvotes: 3

Views: 260

Answers (1)

creanion
creanion

Reputation: 2743

It seems like %reset -f in out is the best option, cleaning up all these variables, without a prompt.

It cleans up the In and Out dictionaries and removes the result variables, including _.

Upvotes: 1

Related Questions