Posts

Showing posts from 2017

Python Decorators

Definition A decorator takes in a function, adds some functionality and returns it. This is similar to packing a gift. The decorator acts as a wrapper. The nature of the object that got decorated (actual gift inside) does not alter. We can use the @ symbol along with the name of the decorator function and place it above the definition of the function to be decorated. def make_pretty(func):     def inner():         print("I got decorated")         func()     return inner def ordinary():     print("I am odinary") >>> ordinary() I am ordinary >>> # let's decorate this ordinary function >>> pretty = make_pretty(ordinary) >>> pretty() I got decorated I am ordinary In the example shown above, make_pretty() is a decorator. @make_pretty def ordinary():     print("I am ordinary") is equivalent to def ord...

Python Closures

Definition The technique by which some data gets attached to the code is called closure in Python. The value in the enclosing scope is remembered even when the variable goes out of scope or the function itself is removed from the current namespace. The criteria that must be met to create closure in Python are summarized in the following points. We must have a nested function (function inside a function). The nested function must refer to a value defined in the enclosing function. The enclosing function must return the nested function. def print_msg(msg):     def printer():         print(msg)     return printer another = print_msg("Hello") >>> another() Hello >>> del print_msg >>> another() Hello >>> print_msg("Hello") Traceback (most recent call last): ... NameError: name 'print_msg' is not defined Use Cases 1. Closures can avoid the use of global values and provides some...

Python Higher Order Functions

Definition Function that take other functions as arguments are also called   higher order functions . def inc(x):     return x + 1 def dec(x):     return x - 1 def operate(func, x):     result = func(x)     return result >>> operate(inc,3) 4 >>> operate(dec,3) 2 Use Cases In functional programming. Courtesy https://www.programiz.com