Originally published at https://www.geeksforgeeks.org
Before seeing what a closure is, we have to first understand what are nested functions and non-local variables.
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 = textdef 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.
A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.
# Python program to illustrateclosures
def outerFunction(text):
text = textdef innerFunction(): print(text) return innerFunction # Note we are returning function WITHOUT parenthesis
if name == ‘main’:
myFunction = outerFunction(‘Hey!’)
myFunction()
Output:
omkarpathak@omkarpathak-Inspiron-3542:
~/Documents/Python-Programs/$ python Closures.py
Hey!
# Python program to illustrateclosures
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))
print(func(*args))
# Necessary for closure to work (returning WITHOUT parenthesis)
return log_funcdef add(x, y):
return x+ydef sub(x, y):
return x-yadd_logger = logger(add)
sub_logger = logger(sub)add_logger(3, 3)
add_logger(4, 5)sub_logger(10, 5)
sub_logger(20, 10)
OUTPUT:
omkarpathak@omkarpathak-Inspiron-3542:
~/Documents/Python-Programs/$ python MoreOnClosures.py
6
9
5
10
Thanks for reading ❤
If you liked this post, share it with all of your programming buddies!
Follow us on Facebook | Twitter
☞ Python Tutorial - Python GUI Programming - Python GUI Examples (Tkinter Tutorial)
☞ Python Tutorial: Image processing with Python (Using OpenCV)
☞ An A-Z of useful Python tricks
#python #function