The Python re.purge() method is used to clear the regular expression cache. Python's re module maintains a cache of compiled regular expressions to improve performance but this cache can grow if many different patterns are compiled. Using the re.purge() method we can clear this cache by freeing up memory and ensuring that old or unused patterns do not remain in memory.
This method is particularly useful in long-running programs or environments where memory usage is a concern such as web servers or applications that compile many unique regular expressions over time.
SyntaxFollowing is the syntax and parameters of Python re.purge() method.
re.purge()Parameter
This method does not take any parameters.
Return valueThis method does not return any values.
Example 1Following is the example of re.purge() method which clears the cache after compiling and using some regular expressions −
import re # Compile some regular expressions pattern1 = re.compile(r'\d+') pattern2 = re.compile(r'\w+') # Use the patterns pattern1.search('123') pattern2.search('abc') # Clear the cache re.purge() # After purge, the cache is empty # Compile the same patterns again pattern1 = re.compile(r'\d+') pattern2 = re.compile(r'\w+') print("Cache cleared and patterns recompiled.")Output
Cache cleared and patterns recompiled.Example 2
This example shows how to measure the memory usage of the regular expression cache before and after using the method re.purge(). This can show the impact of clearing the cache on memory usage −
import re import sys # Compile many regular expressions to fill the cache patterns = [re.compile(rf'\d+_{i}') for i in range(1000)] # Measure memory usage of the cache before_purge = sys.getsizeof(re._cache) # Clear the cache re.purge() # Measure memory usage of the cache after purge after_purge = sys.getsizeof(re._cache) print(f"Memory usage before purge: {before_purge} bytes") print(f"Memory usage after purge: {after_purge} bytes")Output
Memory usage before purge: 36952 bytes Memory usage after purge: 64 bytes
python_modules.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4