1

To remove a variable / object in Python I always use:

del variable
del [variable1, variable2] # removing multiple variables

How can I extend this, so I can delete all variables / objects ending with a certain pattern?

The reason I'm asking is that I'd like to remove all my temporary objects. I always name these such that they end with _tmp.

11
  • 1
    "I'd like to remove all my temporary objects" - but why? Python's garbage collector does this for you. Commented Jul 17, 2019 at 10:48
  • Possible duplicate of Is there a way to delete created variables, functions, etc from the memory of the interpreter? Commented Jul 17, 2019 at 10:48
  • @meowgoesthedog I basically want to do this so the overview in Python's Variable Explorer remains clean. For example, I might create a new dataframe and to do that I first create 5 temporary objects / variables that are then shown in my Variable Explorer. Those 5 objects I would give a name ending with _tmp so that I'd like to delete all those again. Does that make sense? Commented Jul 17, 2019 at 10:52
  • 2
    If they're hanging around making debugging difficult, it suggests you have a much wider scope than you need. For instance make the dataframe in a function, then the variables will be automatically removed from the variable explorer as soon as the function returns. Commented Jul 17, 2019 at 10:57
  • 1
    @Ghassen wasn't me. Although your suggestion doesn't work anyways. Commented Jul 17, 2019 at 11:15

1 Answer 1

3

As an alternative method, but which would solve your problem. you could make use of a dictionary. So if you keep all your temporary objects in a dictionary, you would need to only delete that.

temp_dict = {'variable1_tmp': 1234, 'variable2_tmp': 'hello'}
# remove only one temp
del temp_dict['variable1_tmp']
# remove all temp
del temp_dict

Although that is not dynamically deleting variables, as you asked. Hopefully that might suit your use case anyway.

Sign up to request clarification or add additional context in comments.

1 Comment

Great suggestion, will adopt this in my 'best practice'. It seems to make sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.