Open In App

__closure__ magic function in Python

Almost everything in Python is an object, similarly function is an object too and all the function objects have a __closure__ attribute. __closure__ is a dunder/magic function i.e. methods having two underscores as prefix and suffix in the method name

A closure is a function object that remembers values in enclosing scopes even if they are not present in memory. The __closure__ attribute of a closure function returns a tuple of cell objects. This cell object also has an attribute called cell_contents, which returns the contents of the cell.



Syntax:

closure_function.__closure__

Example:






# this is a nested function
def gfg(raise_power_to):
  
    def power(number):
       return number ** raise_power_to
    return power
 
raise_power_to_3 = gfg(3)
print(raise_power_to_3.__closure__)
 
print(raise_power_to_3.__closure__[0].cell_contents)

Output:

(<cell at 0x7f34ba2725e0: int object at 0x7f34bde02720>,)

3

In the above example, the nested function power has __closure__ attribute associated with it and it returns a tuple of cell objects. The cell_contents attribute returns the value 3 as it was closed inside the cell object.

Article Tags :