Skip to content

Instantly share code, notes, and snippets.

@matthewryanscott
Created December 9, 2009 05:04
Show Gist options
  • Save matthewryanscott/252278 to your computer and use it in GitHub Desktop.
Save matthewryanscott/252278 to your computer and use it in GitHub Desktop.
# Here's a way to "snapshot" the modules already loaded by
# Python, so you can go back to that snapshot at a later point in
# time by causing Python to forget about modules already loaded.
#
# The modules still exist if you have any objects pointing to them,
# but when an import statement or __import__ call is encountered,
# Python will look for the module again and load it as if it were
# never imported in the first place.
#
# This is useful when you lazily import modules, such as in the
# case of setting up clean environments for test cases, rapidly
# iterating over changes to certain aspects of your app's code
# during development, etc.
>>> import sys
>>> old_modules = frozenset(sys.modules)
>>> urllib = __import__('urllib')
>>> id(urllib)
4300206720
>>> urllib_b = __import__('urllib')
>>> id(urllib_b)
4300206720
>>> for key in sys.modules.keys():
... if key not in old_modules:
... del sys.modules[key]
...
>>> urllib_b = __import__('urllib')
>>> id(urllib_b)
4300846704
>>> id(urllib)
4300206720
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment