Skip to content
Related Articles
Open in App
Not now

Related Articles

__closure__ magic function in Python

Improve Article
Save Article
  • Last Updated : 11 Oct, 2020
Improve Article
Save Article

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.





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


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


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.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!