Wednesday, 6 March 2019

Python Closures

Before seeing what a closure is, we have to first understand what are nested functions and non-local variables.

Nested functions in Python
A function which is defined inside another function is known as nested function. Nested functions are able to access variables of the enclosing scope.

In Python, these non-local variables can be accessed only within their scope and not outside their scope. This can be illustrated by following example:

# Python program to illustrate
# nested functions
def outerFunction(text):
text = text
def innerFunction():
print(text)
innerFunction()
if __name__ == '__main__':
outerFunction('Hey!')

As we can see innerFunction() can easily be accessed inside the outerFunction body but not outside of it’s body. Hence, here, innerFunction() is treated as nested Function which uses text as non-local variable.

Python Closures
A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.

1.It is a record that stores a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.

2.A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.

# Python program to illustrate
# closures
def outerFunction(text):
text = text
def innerFunction():
print(text)
return innerFunction # Note we are returning function WITHOUT parenthesis
if __name__ == '__main__':
myFunction = outerFunction('Hey!')
myFunction()

Output:
Hey!
1.As observed from above code, closures help to invoke function outside their scope.
2.The function innerFunction has its scope only inside the outerFunction. But with the use of closures we can easily extend its scope to invoke a function outside its scope

# Python program to illustrate
# closures
import logging
logging.basicConfig(filename='example.log', level=logging.INFO)
def logger(func):
def log_func(*args):
logging.info('Running "{}" with arguments {}'.format(func.__name__, args))
# Necessary for closure to work (returning WITHOUT parenthesis)
return log_func
def add(x, y):
return x+y
def sub(x, y):
return x-y
add_logger = logger(add)
sub_logger = logger(sub)
add_logger(3, 3)
add_logger(4, 5)
sub_logger(10, 5)
sub_logger(20, 10)

Output:
6
9
5
10

When and why to use Closures:
1.As closures are used as callback functions, they provide some sort of data hiding. This helps us to reduce the use of global variables. 2.When we have few functions in our code, closures prove to be efficient way. But if we need to have many functions, then go for class (OOP).

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (49) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (929) Python Coding Challenge (351) Python Quiz (21) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses