How to Clear History in Python

In Python programming, we often need to re-run parts of our code or the entire script where output or behaviors can depend on previous statements. However, we might want to start afresh at some point, effectively clearing the history of statements executed so far.

This tutorial addresses how to do so.

Why Clear the History?

When starting a session/script afresh, clearing history allows you to ensure that you’re executing your code in a ‘clean’ environment, unimpacted by previous commands.

This is very useful when you’re developing and debugging a sequence of commands and you want to be certain that your results aren’t skewed by effects from previous executors.

Using Built-in Python Functions

You can use certain built-in Python functions such as reset() and reset_selective() to clear history. The reset function in Python clears all names defined by the user.

It cleans up the namespace by removing all names defined by the user if called without arguments, or by removing some types of names if called with arguments.

In the above code, var is the variable you want to clear from your history.

Full Code

Please note that Python’s built-in clear function can also be used to clear the data from lists and dictionaries, but it cannot clear the history as the above functions do.

Using System Functions

You can also use system functions such as os.system() to clear scripts. Here, cls is used in Windows, and clear is used in Mac and Linux.

Conclusion

Clearing the history in Python sessions can be essential for debugging and running a script from a clean starting point. Using Python’s built-in functionality combined with the systemic clearing methods, you can comfortably advance in ensuring accurate results for your Python projects.