If Python is running code that seems outdated, a stale cache may be the cause—but “Python cache” can mean several different things. It might refer to compiled .pyc files, modules already loaded into a running process, pip’s downloaded-package cache, or a test tool’s saved results. Each cache has a different purpose and a different way to clear it.
This guide explains how to clear the most common Python caches safely, when doing so can help, and how to stop certain caches from being created again. In most cases, clearing a cache is safe: Python or the relevant tool will rebuild it when needed. You usually do not need to clear every cache to fix one problem.
What Does the Python Cache Do?
Python uses caches to avoid repeating work. When it imports a module, for example, it can save compiled bytecode in a __pycache__ directory. Package managers such as pip keep downloaded files so they do not have to fetch the same packages again. Test runners may save information between runs to make future runs faster.
A cache is not usually the same as a program’s live memory. Deleting a .pyc file does not remove a module that has already been imported into a running Python process. Likewise, clearing pip’s cache does not uninstall packages from your environment. Identifying which cache is involved helps you choose the right fix.
-
Import bytecode cache:
__pycache__folders and.pycfiles. - In-memory import cache: modules and import information held by a running Python process.
- pip cache: downloaded packages and other files saved by pip.
- Tool-specific caches: saved data used by pytest, Jupyter, or other Python tools.
How to Clear Python’s Bytecode Cache
When Python imports a source file, it may create compiled bytecode in a folder named __pycache__. Files in this folder commonly have names ending in .pyc. Python checks whether the cached bytecode matches the source file and normally recompiles it when necessary, so deleting these files is not a routine maintenance requirement. It can help when investigating an unusual import or build issue, or when you want to remove generated files from a project.
From your project’s root directory, you can remove __pycache__ directories and .pyc files with a shell command. On macOS or Linux, run:
find . -type d -name "__pycache__" -prune -exec rm -rf {} +
find . -type f -name "*.pyc" -delete
These commands search from the current directory, so make sure you are in the intended project before running them. The first command removes all matching __pycache__ directories under that location; the second removes any remaining .pyc files.
In Windows PowerShell, run the following from your project directory:
Get-ChildItem -Path . -Directory -Filter "__pycache__" -Recurse |
Remove-Item -Recurse -Force
Get-ChildItem -Path . -File -Filter "*.pyc" -Recurse |
Remove-Item -Force
For a cross-platform approach, use Python itself. This script removes bytecode cache directories and standalone .pyc files below the current directory:
from pathlib import Path
import shutil
root = Path(".")
for path in root.rglob("__pycache__"):
if path.is_dir():
shutil.rmtree(path)
for path in root.rglob("*.pyc"):
if path.is_file():
path.unlink()
Run the script from the project folder you intend to clean. Avoid running it from a broad location such as your home directory unless you specifically want to search everything beneath it. Python may recreate bytecode caches the next time you import the relevant modules.
How to Clear the Cache for One Module
If you only need to remove the bytecode for a particular module, locate its corresponding .pyc file inside __pycache__ and delete that file. The exact filename can include the Python version and interpreter details, so removing a specific file manually may be less convenient than deleting the project’s cache directories.
For a focused cleanup in Python, you can remove a module’s cache directory with pathlib and shutil. Replace the example path with the actual location:
from pathlib import Path
import shutil
cache_dir = Path("my_package/__pycache__")
if cache_dir.exists():
shutil.rmtree(cache_dir)
Only remove files in a project or environment you control. A cache directory is usually safe to delete, but checking the path first helps prevent accidentally removing unrelated files.
How to Clear Python’s In-Memory Import Cache
Deleting .pyc files does not unload modules from a Python process that has already imported them. Python stores imported modules in sys.modules. If you edit a module while a script, application, notebook, or interactive session is still running, that process may continue using the version it already loaded.
The simplest and most reliable solution is to restart the Python process. Stop and rerun your script, restart your development server, or restart the Jupyter kernel. Restarting starts a fresh interpreter and clears its in-memory module state.
In some interactive situations, you can reload a module with importlib.reload():
import importlib
import my_module
importlib.reload(my_module)
Reloading can be useful for development, but it is not a universal substitute for restarting. Other modules may still hold references to old objects, and reloading does not automatically update every reference throughout your program. For a clean test of changed code, a new process is generally more dependable.
If Python cannot find a module that you recently created or added to an import path, the issue may involve finder caches rather than loaded module contents. Ask Python to refresh those caches with:
import importlib
importlib.invalidate_caches()
This tells import finders to check for newly available modules. It does not clear sys.modules, unload already imported modules, or delete bytecode files.
How to Clear the pip Cache
pip caches downloaded packages and related files to speed up future installations. Clearing this cache does not uninstall packages already installed in your Python environment. It may, however, make a later installation slower because pip might need to download files again.
To see where pip stores its cache, run:
python -m pip cache dir
To inspect cached items, use:
python -m pip cache info
python -m pip cache list
To remove pip’s cached files, run:
python -m pip cache purge
Using python -m pip helps ensure that you are running pip for the selected Python interpreter. If you use a virtual environment, activate it first or use that environment’s Python executable. On systems where the command is named python3, substitute python3 in these examples.
If an installation seems to be reusing a problematic cached package, you may be able to retry that installation without using the cache:
python -m pip install --no-cache-dir package-name
This option applies to that installation command; it does not necessarily erase the entire pip cache. It can be a useful troubleshooting step when you suspect a downloaded artifact is corrupted or outdated.
How to Clear the pytest Cache
pytest uses a project cache, often stored in a directory named .pytest_cache, to save information that can help with later test runs. If you want pytest to remove its saved cache and run tests, use:
pytest --cache-clear
You can also delete the project’s .pytest_cache directory manually when pytest is not using it. The directory can be recreated the next time tests run. Clearing it is usually unnecessary unless you are troubleshooting test selection or another cache-related issue.
How to Clear a Jupyter Notebook Cache
Jupyter notebooks can be confusing because the kernel keeps variables and imported modules in memory even after you edit a cell. If the notebook appears to use old code or old values, restart the kernel. In JupyterLab or the classic Notebook interface, use the kernel menu to restart it, then run the cells again in order.
Restarting the kernel clears the session’s in-memory state; it does not normally delete your notebook file or project’s .pyc files. If you also need to remove bytecode caches, use the appropriate cleanup instructions above. When troubleshooting, distinguish between the notebook’s saved output, the active kernel’s memory, and files on disk.
How to Prevent Python from Writing Bytecode Files
If you do not want Python to create .pyc files for a particular run, start Python with the -B option:
python -B my_script.py
You can also set the PYTHONDONTWRITEBYTECODE environment variable. On macOS or Linux, for example:
PYTHONDONTWRITEBYTECODE=1 python my_script.py
In PowerShell, set the variable for the current session before running the script:
$env:PYTHONDONTWRITEBYTECODE = "1"
python my_script.py
Preventing bytecode writes can be useful in certain containers, deployment workflows, or read-only environments. For everyday development, leaving this behavior enabled is generally fine: bytecode caches are designed to improve import performance, and Python manages them automatically.
When Should You Clear a Python Cache?
Clear a cache when you have a specific reason, such as investigating stale behavior, resolving a suspected corrupted download, cleaning generated project files, or resetting saved test state. Choose the smallest action that addresses the problem. For example, restart a notebook kernel for stale in-memory variables; do not purge pip’s cache if the issue is an already imported module.
- Python seems to run old code: restart the process or notebook kernel first.
-
A new module is not detected: check your import path and try
importlib.invalidate_caches(). -
You need to remove generated bytecode: delete the project’s
__pycache__directories and.pycfiles. -
A package download may be corrupted: try installing with
--no-cache-diror purge pip’s cache. -
Tests behave as if old state remains: try
pytest --cache-clearand review the tests’ own setup.
Clearing caches can make the next run slower while files or data are rebuilt. It also will not fix unrelated problems such as importing the wrong package, using a different virtual environment, or editing a file that your program never loads. Check the active Python executable and module path if the issue continues.
Conclusion
To clear a Python cache, first identify which cache you mean. Remove __pycache__ directories to delete compiled bytecode, restart the interpreter to clear in-memory imports, run python -m pip cache purge to clear pip’s downloads, or use pytest --cache-clear for pytest’s saved data. These caches serve different purposes, so a targeted cleanup is safer and more effective than deleting everything. Python and its tools can generally rebuild the files they need the next time they run.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.