Skip to content

Instantly share code, notes, and snippets.

@sshirokov
Created May 22, 2009 03:32
Show Gist options
  • Save sshirokov/115909 to your computer and use it in GitHub Desktop.
Save sshirokov/115909 to your computer and use it in GitHub Desktop.
Functions to use, and generate monkeypatches for classes.
def monkeypatch(target, name = None, func = None, backup_prefix = "default_"):
'''
Decorator.
Binds target.name = func
Creates target.{backup_prefix + name} = target.name if property exists.
This allows the patched properties to depend on the existence of the original
property on the target.
'''
if not func: return lambda func: monkeypatch(target, name, func)
if not name and func.__name__[0] is not '<': name = func.__name__.strip('_')
if hasattr(target, name) and not hasattr(target, backup_prefix + name):
setattr(target, backup_prefix + name, getattr(target, name))
setattr(target, name, func)
return func
def targeted_patch(target):
'''
Decorator generator.
Returns a decorator shorthand equal to monkeypatch(target, func = decorated_function)
Example:
from django.contrib.auth.models import User
user_patch = targeted_patch(User)
@user_patch
def _get_username_questioningly(self):
return self.username + "?"
u = User.objects.get(username = 'bob')
u.get_username_questioningly() #=> 'bob?
'''
return lambda func: monkeypatch(target, func = func)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment