Python — Closures and Decorators

Nandhabalan Marimuthu
2 min readApr 16, 2021

--

Nested Functions:

A function that is defined inside another function is known as a nested function. Nested functions can access variables of the enclosing scope.
In Python, these non-local variables can be accessed only within their scope and not outside their scope.

def fun1(x):
def fun2():
print(x**2)
fun2()
fun1(5)
25

Here the non-local variable x can only be accessed within the enclosing function.

Closures:

The closure method is somewhat like a nested function, the only difference is we are returning the function without the parentheses instead of calling it. Here we are referring the function to another variable so it can be called even if we deleted the original function from the memory (only after referring).

Generally, closure is used for Encapsulation. Let's try the above nested function in the closure method.

def fun1(x):
def fun2():
print(x**2)
return fun2 #Returning instead of calling
a = fun1(5)
del(fun1()) #deleting the Original function
a()
25

Here the function is executed even after deleting the original function.

Decorators:

In python, decorators are used to adding extra functionality to the existing code. They are also known as metaprogramming because of executing extra codes with the existing ones.

Here you can pass a function as an argument of another function, and the syntax is by giving the “@” operator on top of the function.

def fun1(func):
def fun2(x):
func(x)
print(‘hi’,x)
return fun2
@fun1 #calling the original function
def fun3(y):
print( ‘hello’,y)
fun3(‘jon’)
hello jon
hi jon

Here you can see both of the functions executed by just calling a single function.

--

--

No responses yet