From 834817c27bf6b47734d443634a92af97f198756a Mon Sep 17 00:00:00 2001 From: Gaetan Delannay Date: Tue, 25 Mar 2014 22:59:06 +0100 Subject: [PATCH] [Appy] Added class Appy.Hack allowing to elegantly (more than monkey-)patch methods of existing classes. --- __init__.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/__init__.py b/__init__.py index 3df4e31..a2cd311 100644 --- a/__init__.py +++ b/__init__.py @@ -43,4 +43,27 @@ class Object: '''Includes information from p_other into p_self.''' for k, v in other.__dict__.iteritems(): setattr(self, k, v) + +# ------------------------------------------------------------------------------ +class Hack: + '''This class proposes methods for patching some existing code with + alternative methods.''' + @staticmethod + def patch(method, replacement): + '''This method replaces m_method with a p_replacement method, but + keeps p_method on its class under name + "_base__". In the patched method, one may use + Hack.base to call the base method.''' + # Get the class on which the surgery will take place. + klass = method.im_class + # On this class, store m_method under its "base" name. + name = method.im_func.__name__ + baseName = '_base_%s_' % name + setattr(klass, baseName, method) + # Store the replacement method on klass. + setattr(klass, name, replacement) + + @staticmethod + def base(method): + return getattr(method.im_class, '_base_%s_' % method.im_func.__name__) # ------------------------------------------------------------------------------