Basic of Python — Decorators

Nitish Srivastava
6 min readApr 27, 2022

--

Image from Midjourney

Decorators are a powerful and useful tool in Python since it allows programmers to modify the behaviors of function or class. Decorators allow us to wrap another function to extend the behaviors of the wrapped function, without permanently modifying it.

A Basic Example of Decorator:

Example 1 — Basic example of decorator

In the above example, decorator_function(func) is the decorator and showMessage() is the normal function. You can see inside decorator_function, there is an internal function wrapper, which is indicating to showMessage function and that showMessage function is executing on line number 4, between two print statement. Remember, you must return wrapper itself to integrate decorator.

Let see another way of writing decorator.

Example 2 — Decorator as annotation

Above you can see, This code is same as previous code, except way of integration of decorator, just integrate with @ annotation just above the function you want to integrate that decorator.

Let see another example while calling your function multiple times.

Example 3 — Execute showMessage two times through decorator

Let see another example and call your function before first print statement and then between print statement. And see what happened.

Example 4 — Calling function two times before print message and after print message and showing output

Using the above two examples, you can see inside wrapper, whenever I am calling func(), it is executing the showMessage function.

Check what happens if I will write another variable name instead of func.

Example 5 — Example with argument variable’s name changed

You can see in above example, I have changed decorator_function argument name from func to f, and still same output as previous. Line number 1, 3 and 5. There us no specific requirements to give name here. You can set anything.

Let another example with condition. In this example we can see, caller function will only execute when condition is true.

Example 6 — Example with condition.

Above example, you can see in line number 1, I have declared a variable named age with default value 33 and inside wrapper, in line number 5, I have added a condition, that if age > 33 then execute caller function, either not. Now you can see output. It has not executed “Hello World!” message, because condition is false.

What happened when above condition was true?

Example 7— Example with condition. As same as previous but this time it is showing output.

See in output terminal, when condition is true (because age = 34 and age > 33), its executed message “Hello World!”.

Decorators with parameter:

You can also pass parameter to decorators. Which is very helpful, when you have to write some condition for specific function but you want to write one decorator. Like input validation, log creation etc.

Example 8— Example with custom argument

In above image, you can see, in line number 11, I have passed one parameter with decorator age = 34 and a minor change in decorator_function. Now parameter “f” Instead of directly with decorator function, I have passed inside decorator while creating another inner function named as inner_decorator (you can put any name).

You will get error, if you will try to pass “f” directly in decorator_function, like below example.

Example 9— Example of error, if writing argumented decorator wrong way

Or even like this:

Example 10— Example of error, if writing argumented decorator wrong way

You can see, how i am getting directly a compile time error. So better way use as previous correct way as Example 8.

So, where do you think you can use decorator:

Its on your requirement, but just for idea, you can use decorator on below given point. Because this all are basically used on any software application.

  1. To validate user session: — You can use decorator to check if user is logged in or not and only then let them use caller function. Like If session is null, or not valid user session, then prevent user to access internal dashboard.
  2. To validate API’s access token: — In your application/ API, if you want only user with valid access token can access this function, you can validate that function with decorator. Write once for validation and use with every function you want. Example below.
  3. In case of Input Validation: — You can validate if coming request is valid or not and only then let user to execute a function.
  4. To save log after every execution: — You can write a simple code to save every request header and log for every request after execution of that function based on your need.
  5. To handle Exceptions and Errors: — You can also write code to handle different kind of errors.
  6. To manage user/session role:- You can write decorator to check valid user or role is only able to access your api.

Let see an example using Flask:

Step 1 :- import important libraries

Example 11 — Code to import required libraries in Python

Step 2 :- Setup Flask

Example 12 — Setup flask

Step 3 :- Write decorators for as per your need

Below decorator is used to validate x-access-token generated on login.

Example 13 — Decorator to check access token on every api call

Write another decorator to validate data coming from request. You can modify your code as per your need.

Example 14 — Decorator to check required input exists on request or not

Write another decorator to create log after every request. Here I am saving data in text file. You can save data in database.

Example 15 — Decorator to create log after every api executed

Step 4 :- Now, lets use these decorators.

Here in my first example on login API. I am using validate_request decorator to validate input coming with api call.

Example 16 — A login example to generate JWT token

Here, you can see I am passing required parameter to validate_request decorator to check keys username and password available with request or not??? Here Example 14, validate_request, from line number 38 to 44, I am checking input is available or not…

Example 17— Code to validate access token, and only user can access dashboard

And in dashboard API, using token_required decorator, In Example 13, I am first checking if user is passing valid x-access-token then user can access dashboard. This x-access-token is generated at login in previous example (Example 16). Example you can find here — https://github.com/ntshvicky/Decorator-Test

So, i think, now you can understand use of decorator. Next time we will check some example of decorators with Classes. Way is same just how to write decorator class.

Write your own code, different condition, different problems and solve using decorator. Thanks….

(Sorry for grammatical mistakes)

--

--

Nitish Srivastava

Full stack developer, with experience in Java, Spring, Python, Angular, Android, Ionic, Flutter, Blockchain NFT and Cryptocurrency