Sunday, September 5, 2010

Keyword Argument Injection with Python Decorators

In most of the object oriented codes we write, we need to set class variables to the given argument values and this is a very line-consuming thing. See what I mean:

class Test:
def __init__(self, x, y, z, t):
self.x = x
self.y = y
self.z = z
self.t = t
print x,y,z,t


To get over these redundant lines, I found a solution using decorators:

def injectArguments(inFunction):
def outFunction(*args,**kwargs):
_self = args[0]
_self.__dict__.update(kwargs)
inFunction(*args,**kwargs)
return outFunction

class Test:
@injectArguments
def __init__(self, x, y, z, t):
print self.x,self.y,self.z,self.t

@injectArguments
def fonksiyon(self, ad):
print "Ad:",self.ad

t = Test(x=4, y=5, z=6, t=7)
t.fonksiyon(ad="Emre")


args dictionary contains the arguments and kwargs dictionary contains the keyword arguments. arg[0] corresponds to self argument. So what we do is we update self.__dict__ with {'x':4, 'y':5,'z':6,'t':7} where self corresponds to the Test instance. This way, bulky self.x = x, etc. codes are eliminated.

I don't know if any built-it decorator like this exists in Python libraries but it seems like I'll be using this a lot.

No comments: