Login

decorators for creating paramaterized decorators and easy monkeypatching

Author:
fish2000
Posted:
January 25, 2010
Language:
Python
Version:
1.1
Tags:
decorator monkeypatch decoratordecorator functionalprogramming usewithcare
Score:
1 (after 1 ratings)

as with all things related to monkeypatching, the caveat is to use things like these for good, and not for evil.

I wrote these decorators because I did not want to rewrite all of PyAWS -- instead I use these to add some standard/useful methods to the Bag collection that PyAWS uses internally.

AN EXAMPLE:

class PatchMyMonkey:
    pass

@monkeypatch(PatchMyMonkey)
def throwfecesat(self, who="nobody"):
    print "Throwing Feces At: %s" % who

@monkeypatch(PatchMyMonkey)
def nicoderm(self, why="no reason"):
    print "Trying To Quit Because: %s" % why
    return {'why':str(why)}

trampstamp = PatchMyMonkey()
trampstamp.throwfecesat(who="another monkey")
print trampstamp.nicoderm(why="cigarettes are pricey")

A LESS SILLY EXAMPLE:

from pyaws import ecs

@monkeypatch(ecs.Bag, fname='get')
def get(self, param, *args, **kw):
    return self.__dict__.get(param, *args, **kw)
@monkeypatch(ecs.Bag, fname='clearurls')
def clearurls(self, *args, **kw):
    for k, v in self.__dict__.items():
        if isinstance(self.__dict__[k], ecs.Bag):
            self.__dict__[k].clearurls(*args, **kw)
        if type(v) == type([]):
            [ii.clearurls() for ii in self.__dict__[k]]
        if type(v) == type(u''):
            if self.__dict__[k].count(u'http://') > 0:
                self.__dict__[k] = "<URL>"

(amazon's URLs are extremely long, and can muddle your test/log output, hence that last function.)

based on sample code from here and here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from decorator import decorator
from functools import partial

def decoflex(decfac, *args, **kw):
	def wrapped(df, param=None, *args, **kw):
		return partial(df, param, *args, **kw)
	return partial(wrapped, decfac, *args, **kw)

@decoflex
def monkeypatch(cls, f, *args, **kwargs):
	if not hasattr(f, "__name__") and kwargs.get('fname', False):
		setattr(cls, fname, f)
		del kwargs['fname']
	else:
		setattr(cls, f.__name__, f)
	return f

@decorator
def trace(f, *args, **kwargs):
	print "%s :: %s, %s" % (f.__name__, args, kwargs)
	return f(*args, **kwargs)

More like this

  1. Other approach of making middleware (by decorators) by diverman 4 years, 2 months ago
  2. Django Dictionary Model by Morgul 3 years, 12 months ago
  3. safe(r) monkeypatching scheme for django testing by showell 5 years, 6 months ago
  4. DRY custom ModelAdmin.list_display methods with a decorator by exogen 6 years, 8 months ago
  5. EasyFeed class by limodou 8 years, 2 months ago

Comments

Please login first before commenting.