Fundamentals 8 min read

Master Python Closures: Why They Matter and How to Use Them

This article demystifies Python closures, explaining their definition, practical significance, and how they enable functions to retain external variables, with clear examples ranging from simple printers to decorators, and discusses when to apply closures in real-world code.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Closures: Why They Matter and How to Use Them

Closure Concept

We try to understand the concept of a closure. In some languages, when a function is defined inside another function and the inner function references variables from the outer scope, a closure is formed. A closure creates an association between a function and a set of “private” variables that persist across multiple calls.

In some languages, when a function is nested inside another function and the inner function references variables from the outer function, a closure may be created. Closures can be used to create a relationship between a function and a set of “private” variables that persist across calls. — Wikipedia

In plain words, when a function is returned as an object together with external variables, a closure is formed. See the example:

def make_printer(msg):
    def printer():
        print msg  # captures external variable
    return printer  # returns function with captured variable

printer = make_printer('Foo!')
printer()

Languages that treat functions as first‑class objects generally support closures, such as Python and JavaScript.

Understanding Closures

Why do closures exist? A closure’s significance lies in its ability to carry external variables (“private data”). The same function with different captured data can perform different tasks, similar to lightweight interface encapsulation.

Interfaces define a set of constraints on method signatures.
def tag(tag_name):
    def add_tag(content):
        return "<{0}>{1}</{0}>".format(tag_name, content)
    return add_tag

content = 'Hello'
add_tag = tag('a')
print add_tag(content)   # <a>Hello</a>
add_tag = tag('b')
print add_tag(content)   # <b>Hello</b>

In everyday life, closures appear when you use a phone to make a call without caring about the hardware details, or when you dine at a restaurant without knowing how the food is prepared. A class instance can also be viewed as a closure that carries constructor arguments.

When to Use Closures

Closures are common in Python, often hidden inside decorators. A decorator with parameters typically creates a closure to capture those parameters.

# how to define

def wrapper(func1):
    # must accept exactly one function
    return func2  # returns a callable object

# how to use

def target_func(args):
    pass

result = wrapper(target_func)(args)

@wrapper
def target_func(args):
    pass

result = target_func()

If a decorator needs its own arguments, an extra outer layer is added, forming a closure that carries the arguments.

def html_tags(tag_name):
    def wrapper_(func):
        def wrapper(*args, **kwargs):
            content = func(*args, **kwargs)
            return "<{tag}>{content}</{tag}>".format(tag=tag_name, content=content)
        return wrapper
    return wrapper_

@html_tags('b')
def hello(name='Toby'):
    return 'Hello {}!'.format(name)

print hello()          # <b>Hello Toby!</b>
print hello('world')   # <b>Hello world!</b>

A Deeper Look

Every closure object has a __closure__ attribute containing a tuple of cell objects, each storing one of the captured external variables.

def make_printer(msg1, msg2):
    def printer():
        print msg1, msg2
    return printer

printer = make_printer('Foo', 'Bar')
printer.__closure__   # returns cell tuple
printer.__closure__[0].cell_contents  # 'Foo'
printer.__closure__[1].cell_contents  # 'Bar'

The principle is straightforward.

Reference Links

https://www.the5fire.com/closure-in-python.html

http://stackoverflow.com/questions/4020419/why-arent-python-nested-functions-called-closures

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingfunctionsDecorator
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.