Python decorators!

Posts about decorators

  • decorators 1 (this one)
  • decorators 2 – arguments to decorator
  • decorator 3 – more complex decorator
  • decorator 4 – reduce to extend functionality with decorators

One useful things are decorators. At the beginning can be a little intimidating and can confuse you, but are very simple to use once you get them. I made the most simple script I could make for this tutorial (code on github repository python_cheatsheet/decorator.py).

What is a decorator?

It is a function/decorator that can be used more times by different functions using simply a @ and the function name before the function that want to use the decorator

The flow chart of the usage of decorator:

  • make a decorator function that gets another function as argument and that has an inner function that has the arguments of the other function
  • the decorator function returns the innerfunction
  • the other functions have the @ followed by the name of the decorator funcion before the def statement
  • when you call the other functions, they will be passed to the decorator and the arguments will be passed to the inner function of the decorator
  • the code in the other functions is executed
  • the code in the inner function of the decorator is excuted

This way all the other functions will use the same code in the decorator in common, saving code and organizing code better. The code is also more mantainable.

The example

output

The video

Post written by Avatar A python enthusiast

Pygame map editor devlog

The devlog of the Pygame map editor. A work in progress to create a map editor to create maps with tiles with an example of a game that uses these maps. The current version is 1.5 of the map editor and 0.2 of the game, not yet ready for the 1.5 version of the editor (16.9.2020). Repository of the map editor