Monkey patching objects in python

Thursday, May 30, 2013


Every object in Python has a __dict__ member, which stores the object's attributes.
So, you can do something like this:

 class surf(object):  
   def __init__(self, arg1, arg2, **kwargs):  
     #do stuff with arg1 and arg2  
     self.__dict__.update(kwargs)  
 s = surf('arg1', 'arg2', bar=20, baz=10)  
 # Here s is a object of surf with two extra attributes.  


Built-in getattr function

 You can get a reference to a function without knowing its name until run-time, by using the getattr function.
 class Cls():  
   def getfood(self):  
     self.food = ['Cheese', 'Pizza', 'Burger', 'Hotdog', 'Pie', 'Fires']  
     return self.food  
 c = Cls()  
 print getattr(c, 'getfood')() 

The output of following code will be
 ['Cleese', 'Palin', 'Idle', 'Gilliam', 'Jones', 'Chapman']

Devide a list in n sized chunks.

Friday, May 24, 2013


Here is the method to devide list in to chunks of n size
 def chunks(list, size):  
   for i in xrange(0, len(list), size):  
     yield list[i:i+size]  
 for list in list(chunks(product_without_season, 1000)):  
   print list