Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add monkey patches structure. #628

Open
huxuan opened this issue Jul 1, 2024 · 0 comments
Open

Add monkey patches structure. #628

huxuan opened this issue Jul 1, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@huxuan
Copy link
Member

huxuan commented Jul 1, 2024

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 huxuan added the enhancement New feature or request label Jul 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant