Closures and Decorators in Python-Part One

In this article, you will get a basic idea about closures and decorators in python and how to use them. In this article, you will get a basic idea about the usage of closures and decorators.

Closures in Python

In Python, all local functions have access to variables in their enclosing scopes. Closures are functions that return other functions, thereby giving them the name – function factory. They take in arguments and return functions with their own local arguments along with the arguments passed through closure. It is a method of binding data to a function without passing them as parameters.

*args and **kwargs in Python

*args in Python allows us to pass a variable number of arguments into our functions. It is used in cases when any or an arbitrary number of arguments can be passed into a function. Similarly, **kwargs allows the user to pass a variable amount of keyword arguments into the function.

As an example, the following functions give us the below-given results:

*args and **kwargs can be used together as well with args followed by kwargs. If any other parameters are also present then they are always written before *args.

Decorators in Python

A decorator, in Python, is a callable that takes another function as its argument. As the name suggests, decorators exist to modify functions and their arguments before the call to the function usually begins. They may perform some processing on the function arguments, or add or remove arguments or return an enhanced or a different function after pre-processing for a ‘decorated’ implementation.

For all functional purposes,

Is the same as

Thus decorators are, up to a very large extent, a syntactical sugar that exists to make your code seem cleaner and increase readability. In the context of Design Patterns, decorators dynamically alter the functionality of a function, method or class without having to directly use subclasses.

Where could these be used?

Decorators have a place in almost in every real-world application. They are often used for logging, timing and authentication purposes along with various other uses.

*args and **kwargs can be used to pass arguments into decorated functions, and along with the power of closures, other possibilities open up. We’ll cover the rest of it in the next tutorial.

Well, that’s it for this article but there will be more articles on this topic. If you want to give any feedback or ask something, just comment below.

Leave a Comment

Your email address will not be published. Required fields are marked *

Share This
Scroll to Top