Recently I came across python closures. I know closures in javascript. However I didnt know closure exists in python too.
A closure in Python is a function object that has access to variables in the outer (enclosing) function’s scope, even after the outer function has finished executing.
A concise video on closure is here on youtube.
Whats the Use of Closure?
One of the usecase I could think of is caching. Lets say you make a call to an API and you want to cache the result and work off the cache, this is going to be very usefule.
Following is an example of it.
from collections import namedtuple
def get_api_handler():
cache:str = None
if(cache == None):
print("Fetching from API and loading the cache")
cache = "Hello World"
def get_value():
print("Fetching from cache")
return cache
api_handler = namedtuple('api_handler',['get_response'])
return api_handler(get_value)
def main():
api_handler = get_api_handler()
api_handler.get_response()
api_handler.get_response()
if __name__ == "__main__":
main() First time when you do api_handler.get_response(), API is called and cache is loaded. Subsequent requests will be served from the cache.
Now, I am also using another concept of python called namedtuple to treat closure like object. You can refer to this youtube video for the same.
Ending Note
Closure is a very powerful feature offered by languages. Different use cases can be implemented with the help of closure. We explored caching as one of the usecase. Other usecases as I know are implementing function factories, encapsulation of private variables, decorators.










