2.7. Closures

2.7.1. Nested Function

  • Function inside the function

  • nested functions can access the variables of the enclosing scope

def run():
    lastname = 'Twardowski'

    def hello():
        print(lastname)

    return hello

hello()
# NameError: name 'hello' is not defined

run()
# <function __main__.run.<locals>.hello()>

hello = run()
hello()
# Twardowski

2.7.2. What is closure?

  • technique by which the data is attached to some code even after end of those other original functions is called as closures

  • Closures can avoid use of global variables and provides some form of data hiding

  • When the interpreter detects the dependency of inner nested function on the outer function, it stores or makes sure that the variables in which inner function depends on are available even if the outer function goes away

  • Method of binding data to a function without actually passing them as parameters is called closure

  • It is a function object obj that remembers values in enclosing scopes even if they are not present in memory

  • Closures provide some sort of data hiding as they are used as callback functions

  • This helps us to reduce the use of global variables

  • Useful for replacing hard-coded constants

  • Closures prove to be efficient way when we have few functions in our code

firstname = 'Jan'
lastname = 'Twardowski'

def hello():
    print(firstname)
    print(lastname)

hello()
# Jan
# Twardowski
firstname = 'Jan'

def run():
    lastname = 'Twardowski'

    def hello():
        print(firstname)
        print(lastname)

    return hello


hello = run()
hello()
# Jan
# Twardowski
firstname = 'Jan'

def run():
    lastname = 'Twardowski'

    def hello():
        print(firstname)
        print(lastname)

    return hello


hello = run()
del run
hello()
# Jan
# Twardowski
def f(x):
    def g(y):
        return x + y
    return g

2.7.3. Assignments

2.7.3.1. Function Closure Check

English
  1. Define function check which takes func: Callable as an argument

  2. Define closure function wrapper inside check

  3. wrapper function takes *args and **kwargs as arguments

  4. Function check must return wrapper: Callable

  5. Call check and get pointer to wrapper

  6. Delete check using del keyword

  7. Call pointer

Polish
  1. Zdefiniuj funkcję check, która przyjmuje func: Callable jako argument

  2. Zdefiniuj funkcję closure wrapper wewnątrz check

  3. Funkcja wrapper przyjmuje *args i **kwargs jako argumenty

  4. Funkcja check ma zwracać wrapper: Callable

  5. Wywołaj check i przechwyć wskaźnik do wrapper

  6. Skasuj check za pomocą słowa kluczowego del

  7. Wywołaj wskaźnik