A guide to Python Closures

A guide to Python Closures

In this article, you'll learn what is a Python closure, how to define a closure, and reasons why you should use it.

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.

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.

  • 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.
  • 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:
[email protected]:
~/Documents/Python-Programs/$ python Closures.py 
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))  print(func(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:
[email protected]:
~/Documents/Python-Programs/$ python MoreOnClosures.py 
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). 

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

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

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Basic Data Types in Python | Python Web Development For Beginners

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Python's reduce(): From Functional to Pythonic Style – Real Python

Python's reduce(): From Functional to Pythonic Style – Real Python

Python Lambda Functions

Python Lambda Functions. Python lambda functions are an invaluable feature. One of the benefits of using Python is that it facilitates a relatively compact code structure compared to other programming languages. This means getting so much more done with fewer lines of code. One such tool is the lambda function. These allow us to create anonymous functions in python.

Learn to Write Better Code in Our Python Advanced Functions Course

Learning to write better code — code that's readable, maintainable, and debuggable — is a crucial skill for being an effective part of a data science team.

Functional Programming: Reduce() Function in Python

Reducing sequence to a single output value! Functional Programming: Reduce() Function in Python. In the previous string of articles, I have talked about the importance of immutable data structures in functional programming. I have also covered the filter() function in the last article. Let’s start from where we left. In this article, I will be talking about the reduce() function.