Login

decorators for creating paramaterized decorators and easy monkeypatching

Author:
fish2000
Posted:
January 25, 2010
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.