Month: March 2015

Python useful code

lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
flattenList(lst) –> [1, 2, 3, 4, 5, 6, 7, 8]

def flattenList(lst):

return sum( ([x] if not isinstance(x, list) else flattenList(x)

for x in lst), [] )

zip function:

first = [1,2,3,4,5]
second = [6,7,8,9,10]
three = [7,9,11,13,15]
[x + y for x, y in zip(first, second)] 

super() in python

super(type[, object-or-type])   class.__mro__:  This attribute is a tuple of classes that are considered when looking for base classes during method resolution.

this can be used to get the method resolution order for both getattr() and super()

One pitfall about super() that I encountered: when using super() in a derived class , do not user super( self.__class__ ,self), which will result recursive loop in certain case (derived class has a child class too, and the child class is calling super() in the same method) the reason is self.__class__ will point to the instance class type.

this issue is also discussed here:

self.__class__ might not be a subclass, but rather a grandchild-or-younger class, leading to a stack-breaking loop.”   Another use case for super() is in multiple inheritance case:

Another great article about how to use super() in python correctly: