Skip to content

Instantly share code, notes, and snippets.

@jwass
Last active August 29, 2015 14:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jwass/05720e8804502a0f86ad to your computer and use it in GitHub Desktop.
Save jwass/05720e8804502a0f86ad to your computer and use it in GitHub Desktop.
Logging imported Python modules

Quick idea to understand what modules get imported.

Example:

>>> import importlog

# Run a bunch of code
>>> import shapely.geometry
>>> p = shapely.geometry.Point(0.0, 0.0)
>>> b = p.buffer(1.0)

# See which modules were imported.
>>> importlog.modules
{'array',
 'ctypes',
 'difflib',
 'future_builtins',
 'numbers',
 'numpy',
 'shapely',
 'unittest'}
import sys
modules = set()
class ImportLog(object):
def find_module(self, fullname, path=None):
name = fullname.split('.')[0]
modules.add(name)
# Returning None just continues import normally
return None
log = ImportLog()
sys.meta_path = [log]
@jwass
Copy link
Author

jwass commented Apr 30, 2015

What's unittest doing there?

@sgillies
Copy link

I wrote a lot of the tests before I got clued in to nose and py.test. It's a standard lib module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment