Skip to content

Instantly share code, notes, and snippets.

@TURBODRIVER
Last active December 19, 2022 01:56
Show Gist options
  • Save TURBODRIVER/8bd0d1194be179a1309496c730b5b188 to your computer and use it in GitHub Desktop.
Save TURBODRIVER/8bd0d1194be179a1309496c730b5b188 to your computer and use it in GitHub Desktop.
import inspect
from functools import wraps
def inject(target_object, target_function_name, safe=False):
if safe and not hasattr(target_object, target_function_name):
def _self_wrap(wrap_function):
return wrap_function
return _self_wrap
def _wrap_original_function(original_function, new_function):
@wraps(original_function)
def _wrapped_function(*args, **kwargs):
if type(original_function) is property:
return new_function(original_function.fget, *args, **kwargs)
else:
return new_function(original_function, *args, **kwargs)
if inspect.ismethod(original_function):
if hasattr(original_function, '__self__'):
return _wrapped_function.__get__(original_function.__self__, original_function.__self__.__class__)
return classmethod(_wrapped_function)
elif type(original_function) is property:
return property(_wrapped_function)
else:
return _wrapped_function
def _injected(wrap_function):
original_function = getattr(target_object, target_function_name)
setattr(target_object, target_function_name, _wrap_original_function(original_function, wrap_function))
return wrap_function
return _injected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment