Example: Naively Track Imports

Sometimes you may want to track what is getting imported when you make a call. Here’s how you can do it.

import_tracker.py:

import sys
class ImportTracker:
    def __init__(self):
        self.modules = []
    def find_module(name, path=None):
        self.modules.append(name)
    def enable(self):
        sys.meta_path.insert(0, self)
    def disable(self):
        sys.meta_path.remove(self)

some_module.py:

from import_tracker import ImportTracker
tracker = ImportTracker()
tracker.enable()
...
print(tracker.modules)

Example: Import Tracking, Take 2

Check out the code here.

Interestingly, the behavior is different for this example if you use importlib’s __import__ vs. the default builtins.__import__. This is because of how sys.modules is treated differently between the two.

Example: Statement Local Namespaces

Go take a look here.

Example: Protecting a High-Latency Filesystem

Sometimes you have in your sys.path a directory from a network drive (perhaps an NFS mount) or other IO-restricted device. In that case you may to limit how import looks for files to mitigate the number of stat calls. Here’s a simple example of how to do so:

... (placeholder)

? lots of stat calls during normal imports?

Example: Customizing Access to a Specific Module Path

  • using sys.path_hooks (placeholder)

Example: PEPS 382 and 402 as Import Hooks

Both of these will work as import hooks

PEP 382 (placeholder)

PEP 402 (placeholder)

Example: Import Engine as an Import Hook

maybe... (placeholder)

Example: lazy imports

Example: “importing” straight from a file

http://code.activestate.com/recipes/577792/