And I can't get anything I write to work.

I'm so far off course I think I just need a working example of import hooks in action.

I've looked for examples on the Internet, but they only show what looks like correct code. They never show that code in action. They never try to import something and show what their hook does.

Actually, please feel free to contribute help, but I managed to create a working example of an import hook.

class Restricted:

    def __init__(self):
        print("Initializing...")
        self.forbidden = list()

    def find_module(self, module_name, package_path):
        if package_path:
            print("Searching the path... Return.")
            return
        if module_name in self.forbidden:
            return self

    def load_module(self, module_name):
        raise ImportError

import sys

sys.meta_path.append(Restricted())
print(sys.meta_path)
sys.meta_path[0].forbidden.append('random')
print(sys.meta_path[0].forbidden)
import random
print(random.random())

The problem occurred when I executed the program from the Python IDLE, but when I executed the program from the command line it worked.

IDLE output:

Initializing...
[<__main__.Restricted object at 0x0000000003C6A9E8>]

0.114156604708

Command line output:

Initializing...
[<__main__.Restricted object at 0x0000000002F69400>]

Traceback <most recent call last>"
File "C:\Users\lrh9\Documents\Code\Personal Code\test.py", line 23, in <module>
import random
File "C:\Users\lrh9\Documents\Code\Personal Code\test.py", line 15, in load_module
raise ImportError
ImportError

Strange.

My first guess about what happened would be that the IDLE imports random when it starts. It probably has the random module all ready cached. If a module is cached, importing it will merely result in the cached module's finder being used and/or the cached module being returned. This would skip the new hook you've inserted.

I bet that if I had reloaded the random module, it would have worked in the IDLE.

Time to test.

That is in fact the case.

To fix this behavior, it would simply be a matter of looping through the built-in modules if that dictionary exists and reloading them.

Now I need to determine how to accomplish that.

This question has already been answered. Start a new discussion instead.