ss-python icon indicating copy to clipboard operation
ss-python copied to clipboard

Add monkey patches structure.

Open huxuan opened this issue 1 year ago • 0 comments

We tend to have monkey patch requirements, let us implement a basic structure for it.

The basic structure contains the following:

  • A patch example <module_name>.patches.patch_example
  • Import all patches in <module_name>.patches.__init__
  • Apply patches in <module_name>.__init__
# <module_name>.patches.patch_example
import some_module

def apply_patches():
    original_function = some_module.some_function

    def patched_function(*args, **kwargs):
        # Add pre-processing here
        print("Patched function is called.")
        result = original_function(*args, **kwargs)
        # Add post-processing here
        return result

    some_module.some_function = patched_function

apply_patches()
# <module_name>.patches.__init__
import os
import importlib.util

def import_all_modules():
    # Get the directory of the current script
    current_directory = os.path.dirname(__file__)
    
    # Get all Python files in the current directory
    module_files = [f for f in os.listdir(current_directory) if f.endswith('.py') and f != '__init__.py' and f != os.path.basename(__file__)]
    
    modules = {}
    for module_file in module_files:
        module_name = module_file[:-3]  # Strip the .py extension
        module_path = os.path.join(current_directory, module_file)
        
        # Load the module
        spec = importlib.util.spec_from_file_location(module_name, module_path)
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)
        
        # Store the loaded module in the dictionary
        modules[module_name] = module
    
    return modules

# Usage example
modules = import_all_modules()

# Now you can access the imported modules via the `modules` dictionary
print(modules)
# <module_name>.__init__
from <module_name> import patches  # This applies the patches

huxuan avatar Jul 01 '24 08:07 huxuan