5 python features I wish I had known earlier
shivashish thakur
Posted on April 28, 2020
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.
- 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.
- def memoize(f):
- def memf(*x):
- if x not in memf.cache:
- memf.cache[x] = f(*x)
- return memf.cache[x]
- memf.cache = {}
- return memf
This can be called as follows:
- recursive_function = memoize(recursive_function)
And viola, the recursive_function is now memorized.
- lst = [ i*i for i in xrange(10)]
Compare this with the one below
- lst = []
- for i in xrange(10):
- lst.append(i*i)
These features add to the richness of the language.
- square = lambda x:x**2
- map(square,[1,2,3]) ## returns [1, 4, 9]
- is_divisible_by_3 = lambda x:x%3==0
- filter(is_divisible_by_3,[1,2,3,4,5,6]) ## returns [3,6]
- reduce(min,[1,2,3,4,5,6]) ## returns 1, you can as well use min([1,2,3,4])
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.
- path = "/home"
- for files os.walk(path):
- print files
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.
Posted on April 28, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.