Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Closures
Next article icon

Python Closures

Last Updated : 11 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, a closure is a powerful concept that allows a function to remember and access variables from its lexical scope, even when the function is executed outside that scope. Closures are closely related to nested functions and are commonly used in functional programming, event handling and callbacks.

A closure is created when a function (the inner function) is defined within another function (the outer function) and the inner function references variables from the outer function. Closures are useful when you need a function to retain state across multiple calls, without using global variables.

A Basic Example of Python Closures

Let's break down a simple example to understand how closures work.

Python
def fun1(x):        # This is the outer function that takes an argument 'x'     def fun2(y):                # This is the inner function that takes an argument 'y'         return x + y  # 'x' is captured from the outer function          return fun2  # Returning the inner function as a closure  # Create a closure by calling outer_function closure = fun1(10)  # Now, we can use the closure, which "remembers" the value of 'x' as 10 print(closure(5))  

Output
15 

Explanation:

  • Outer Function (fun1): Takes an argument x and defines the fun2. The fun2 uses x and another argument y to perform a calculation.
  • Inner Function (fun2): This function is returned by fun1 and is thus a closure. It "remembers" the value of x even after fun1has finished executing.
  • Creating and Using the Closure: When you call fun1(10), it returns fun2 with x set to 10. The returned fun2(closure) is stored in the variable closure. When you call closure(5), it uses the remembered value of x (which is 10) and the passed argument y (which is 5), calculating the sum 10 + 5 = 15.

Let's take a look at python closure in detail:

Example of Python closure:

Python
def fun(a):     # Outer function that remembers the value of 'a'     def adder(b):         # Inner function that adds 'b' to 'a'         return a + b     return adder  # Returns the closure  # Create a closure that adds 10 to any number val = fun(10)  # Use the closure print(val(5))   print(val(20))   

Output
15 30 

In this example:

  • fun(10) creates a closure that remembers the value 10 and adds it to any number passed to the closure.

How Closures Work Internally?

When a closure is created, Python internally stores a reference to the environment (variables in the enclosing scope) where the closure was defined. This allows the inner function to access those variables even after the outer function has completed.

In simple terms, a closure "captures" the values from its surrounding scope and retains them for later use. This is what allows closures to remember values from their environment.

Use of Closures

  • Encapsulation: Closures help encapsulate functionality. The inner function can access variables from the outer function, but those variables remain hidden from the outside world.
  • State Retention: Closures can retain state across multiple function calls. This is especially useful in situations like counters, accumulators, or when you want to create a function factory that generates functions with different behaviors.
  • Functional Programming: Closures are a core feature of functional programming. They allow you to create more flexible and modular code by generating new behavior dynamically.

Next Article
Python Closures

K

kartik
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

    range() vs xrange() in Python
    The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(
    4 min read
    Using Else Conditional Statement With For loop in Python
    Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while
    2 min read
    Iterators in Python
    An iterator in Python is an object that holds a sequence of values and provide sequential traversal through a collection of items such as lists, tuples and dictionaries. . The Python iterators object is initialized using the iter() method. It uses the next() method for iteration.__iter__(): __iter__
    3 min read
    Iterator Functions in Python | Set 1
    Perquisite: Iterators in PythonPython in its definition also allows some interesting and useful iterator functions for efficient looping and making execution of the code faster. There are many build-in iterators in the module "itertools". This module implements a number of iterator building blocks.
    4 min read
    Converting an object into an iterator
    In Python, we often need to make objects iterable, allowing them to be looped over like lists or other collections. Instead of using complex generator loops, Python provides the __iter__() and __next__() methods to simplify this process.Iterator Protocol:__iter__(): Returns the iterator object itsel
    5 min read
    Python | Difference between iterable and iterator
    Iterable is an object, that one can iterate over. It generates an Iterator when passed to iter() method. An iterator is an object, which is used to iterate over an iterable object using the __next__() method. Iterators have the __next__() method, which returns the next item of the object. Note: Ever
    3 min read
    When to use yield instead of return in Python?
    The yield statement suspends a function's execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of v
    2 min read
    Generators in Python
    Python generator functions are a powerful tool for creating iterators. In this article, we will discuss how the generator function works in Python.Generator Function in PythonA generator function is a special type of function that returns an iterator object. Instead of using return to send back a si
    5 min read
    Python Functions
    Python Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an
    9 min read
    Returning Multiple Values in Python
    In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python # A Python program to return multiple # values from a meth
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences