DEV Community

Cover image for 5 python features I wish I had known earlier
shivashish thakur
shivashish thakur

Posted on

5 python features I wish I had known earlier

There are several helpful concepts in Python that I knew about from the origin: such as generators, iterators, context managers, and so on, but there are many features that are not obvious until you met them. I essentially use Python 2.6-2.7 for writing small cross-platform (including windows) text processing console utilities, and here are several of my favorites.

  1. MEMORIZATION:

One can take the guidance of the functional programming technique in Python and build memorizers [like the one below], which could probably take any recursive function as an input and return a memoized version of it, which makes the code to run significantly quicker.

  1. def memoize(f):
  2.    def memf(*x):
  3.        if x not in memf.cache:
  4.            memf.cache[x] = f(*x)
  5.        return memf.cache[x]
  6.    memf.cache = {}
  7.    return memf

This can be called as follows:

  1. recursive_function = memoize(recursive_function)

And viola, the recursive_function is now memorized.

 

  1. LIST COMPREHENSIONS:

 

  1. lst = [ i*i for i in xrange(10)]

Compare this with the one below

  1. lst = []
  2. for i in xrange(10):
  3. lst.append(i*i)

 

  1. LAMBDAS, MAP, REDUCE AND FILTERS:

These features add to the richness of the language.

  1. square = lambda x:x**2
  2. map(square,[1,2,3]) ## returns [1, 4, 9]
  3. is_divisible_by_3 = lambda x:x%3==0
  4. filter(is_divisible_by_3,[1,2,3,4,5,6]) ## returns [3,6]
  5. reduce(min,[1,2,3,4,5,6]) ## returns 1, you can as well use min([1,2,3,4])

 

  1. GENERATORS:

Ever required to iterate over a very wide collection of items like your linux file-system tree. Generators make life more comfortable for you.

This is an easy code snippet that uses walk function from the os module and prints out all files and directors available starting from the root directory. os.walk() is a generator function which supplies the following item to be iterated upon freezes its context and goes into a suspended state, the next time when the next iteration is to be performed it supplies the next item and goes back into the frozen state again until when all items are utilized, in which instance it returns a StopIteration exception.

  1. path = "/home"
  2. for files os.walk(path):
  3.     print files

 

  1. DEBUGGER:

Python gives a pdb module, an simple to use, and extremely helpful debugger.

Just type import pdb; pdb.set_trace() to set a breakpoint wherever in your code.

Explore more python projects and get your concepts clear. 

Latest comments (1)

Collapse
 
aderchox profile image
aderchox

"And viola, the recursive_function is now memorized." What does that mean? The memorization isn't clear. The rest are clear thanks.