|
| 1 | +"""Generic monkey-patching utilities.""" |
| 2 | + |
| 3 | +from contextlib import ContextDecorator |
| 4 | +from functools import wraps |
| 5 | +from typing import Callable, TypeVar |
| 6 | + |
| 7 | +T = TypeVar("T") |
| 8 | + |
| 9 | + |
| 10 | +class MonkeyPatch(ContextDecorator): |
| 11 | + """Context manager for temporarily patching methods on classes. |
| 12 | +
|
| 13 | + This is a clean, reusable utility for monkey-patching that doesn't |
| 14 | + know anything about the specific framework or use case. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + target_cls: type, |
| 20 | + method_name: str, |
| 21 | + wrapper_fn: Callable[[Callable], Callable], |
| 22 | + ): |
| 23 | + """Initialize the monkey patch. |
| 24 | +
|
| 25 | + Args: |
| 26 | + target_cls: The class to patch |
| 27 | + method_name: Name of the method to patch |
| 28 | + wrapper_fn: Function that takes the original method and returns a wrapped version |
| 29 | + """ |
| 30 | + self.target_cls = target_cls |
| 31 | + self.method_name = method_name |
| 32 | + self.wrapper_fn = wrapper_fn |
| 33 | + self.patched_items = [] |
| 34 | + |
| 35 | + def __enter__(self): |
| 36 | + """Apply the monkey patch.""" |
| 37 | + # Patch the target class and all its subclasses |
| 38 | + for cls in {self.target_cls, *self.target_cls.__subclasses__()}: |
| 39 | + original_method = getattr(cls, self.method_name, None) |
| 40 | + if original_method is not None: |
| 41 | + # Mark the original method so we can detect it |
| 42 | + if not hasattr(original_method, "_monkey_patch_original"): |
| 43 | + wrapped_method = self.wrapper_fn(original_method) |
| 44 | + wrapped_method._monkey_patch_original = original_method |
| 45 | + setattr(cls, self.method_name, wrapped_method) |
| 46 | + self.patched_items.append((cls, self.method_name, original_method)) |
| 47 | + return self |
| 48 | + |
| 49 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 50 | + """Restore the original methods.""" |
| 51 | + for cls, method_name, original_method in self.patched_items: |
| 52 | + setattr(cls, method_name, original_method) |
| 53 | + self.patched_items.clear() |
| 54 | + |
| 55 | + |
| 56 | +def create_wrapper( |
| 57 | + decorator_fn: Callable, |
| 58 | + should_skip: Callable[[tuple, dict], bool] | None = None, |
| 59 | + **decorator_kwargs, |
| 60 | +) -> Callable[[Callable], Callable]: |
| 61 | + """Create a wrapper function that applies a decorator conditionally. |
| 62 | +
|
| 63 | + Args: |
| 64 | + decorator_fn: The decorator to apply (e.g., prefect.task) |
| 65 | + should_skip: Optional function to determine if decoration should be skipped |
| 66 | + **decorator_kwargs: Keyword arguments to pass to the decorator |
| 67 | +
|
| 68 | + Returns: |
| 69 | + A wrapper function suitable for use with MonkeyPatch |
| 70 | + """ |
| 71 | + |
| 72 | + def wrapper_factory(original_method: Callable) -> Callable: |
| 73 | + # Check if original method is async |
| 74 | + import inspect |
| 75 | + |
| 76 | + is_async = inspect.iscoroutinefunction(original_method) |
| 77 | + |
| 78 | + if is_async: |
| 79 | + |
| 80 | + @wraps(original_method) |
| 81 | + async def async_wrapper(*args, **kwargs): |
| 82 | + # Check if we should skip decoration |
| 83 | + if should_skip and should_skip(args, kwargs): |
| 84 | + return await original_method(*args, **kwargs) |
| 85 | + |
| 86 | + # Apply the decorator |
| 87 | + decorated = decorator_fn(**decorator_kwargs)(original_method) |
| 88 | + result = decorated(*args, **kwargs) |
| 89 | + if hasattr(result, "__await__"): |
| 90 | + return await result |
| 91 | + return result |
| 92 | + |
| 93 | + return async_wrapper |
| 94 | + else: |
| 95 | + |
| 96 | + @wraps(original_method) |
| 97 | + def sync_wrapper(*args, **kwargs): |
| 98 | + # Check if we should skip decoration |
| 99 | + if should_skip and should_skip(args, kwargs): |
| 100 | + return original_method(*args, **kwargs) |
| 101 | + |
| 102 | + # Apply the decorator |
| 103 | + decorated = decorator_fn(**decorator_kwargs)(original_method) |
| 104 | + return decorated(*args, **kwargs) |
| 105 | + |
| 106 | + return sync_wrapper |
| 107 | + |
| 108 | + return wrapper_factory |
0 commit comments