Skip to content
Related Articles

Related Articles

__closure__ magic function in Python
  • Last Updated : 11 Oct, 2020

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 returns the contents of the cell.

Syntax:

closure_function.__closure__

Example:

Python



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :