importhook

Python module for registering hooks to call when certain modules are imported.

import importhook

# Configure a function to call when `socket` is imported
@importhook.on_import('socket')
def socket_import(socket):
    print('Socket module imported')

# Import the `socket` module
import socket
importhook.copy_module(module, copy_attributes=True, copy_spec=True)

Helper function for copying a python module

import importhook

@importhook.on_import('socket')
def on_socket_import(socket):
    new_socket = importhook.copy_module(socket)
    setattr(new_socket, 'get_hostname', lambda: 'hostname')
    return new_socket
importhook.get_module_name(module)

Helper function to get a module’s name

importhook.on_import(module_name, func=None)

Helper function used to register a hook function for a given module

import importhook

@importhook.on_import('socket')
def on_socket_import(socket):
    print('socket imported')


@importhook.on_import(importhook.ANY_MODULE)
def on_any_import(module):
    print(f'{module.__spec__.name} imported')


def on_httplib_import(httplib):
    print('httplib imported')


importhook.on_import('httplib', on_httplib_import)
importhook.reload_module(module_name)

Helper function to reload the specified module

import socket
import importhook

# Reload the `socket` module by passing in module
socket = importhook.reload_module(socket)

# Reload the `socket` module by passing in the name
socket = importhook.reload_module('socket')
importhook.reset_module(module_name)

Helper function to reset a copied module.

import socket
import importhook

# Copy `socket` module
socket = importhook.copy_module(socket)

# Reset copied `socket` module back to it's original version
socket = importhook.reset_module(socket)