Decorators in Python

What is a decorator ?

decorator in Python is any callable Python object that is used to modify a function or a class. A reference to a function “func” or a class “C” is passed to a decorator and the decorator returns a modified function or class.

Sample Program of Decorator

def decorator_function(func):
    def msg():
        print("Hey...")
        func()
    return msg

@decorator_function
def deco1():
    print("This is a decorator function.")

deco1()

def deco2():
    print("This is also a decorator function")


# abc = decorator_function(deco2)
# abc()

*args and **kwargs in Python

*args – The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list.

**kwargs – The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is because the double star allows us to pass through keyword arguments (and any number of them).

Sample Program using both *args and **kwargs

def f(*args, **kwargs):
    if kwargs.get('reverse_str') == True:
        return [i[::-1].title() for i in args]
    else:
        return [i.title() for i in args]

a = ['sayan', 'dey']
print(f(*a, reverse_str = True))

sort() and sorted() in Python

# names = ["Sayan", "Dey", "SD"]
# names.sort()
# print(names)

# Not possible to sort names in Tuples or Sets

# names1 = ("Sayan", "Dey", "SD")
# sorted(names1)
# print(names1)

# names2 = {"Sayan", "Dey", "SD"}
# sorted(names2)
# print(names2)

dictionary = [
    {"name" : "Sayan", 
    "stream" : "MCA", 
    "roll" : 11, 
    "marks" : 99},

    {"name" : "Dey", 
    "stream" : "MCA", 
    "roll" : 12, 
    "marks" : 79},

    {"name" : "SD", 
    "stream" : "MCA", 
    "roll" : 13, 
    "marks" : 98},
]

print(sorted(dictionary, key = lambda d:d.get('marks'), reverse = True))
print(sorted(dictionary, key = lambda d:d['marks'], reverse = True))

logspace() in Python

Syntax : numpy.logspace(start, stop, num = 50, endpoint = True, base = 10.0, dtype = None)

Def : Returns number spaces evenly w.r.t interval on a log scale.

Sample Program

import numpy as py

arr = py.logspace(1, 8, num=5, base=10, dtype=int)

for elements in arr:
    print(elements)

for elements in range(len(arr)):
    print(arr[elements], end = " ")

linspace() in Python

Syntax : numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None)

Def : Returns number spaces evenly w.r.t interval. Similar to arange but instead of step it uses sample number.

Sample Program

import numpy as py

arr = py.linspace(1, 8, num=5, dtype=int, endpoint=False)

for items in arr:
    print(items)

for items in range(len(arr)):
    print(arr[items])