I
I
Ivanzolo20012021-11-13 14:28:15
Python
Ivanzolo2001, 2021-11-13 14:28:15

How are decorators implemented in aiogram?

Now I started writing bots on aiogram, the question is: How are the decorated functions called? In the usual examples about decorators, it is necessary to CALL this very decorated function, but in aiograms it works in a strange way for me. Why do decorated functions even work if I don't call them? To make you understand what I mean, imagine a regular decorator on the start command.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-11-13
@Ivanzolo2001

Functions (like methods) in python are objects of the first kind, they can be stored in variables, passed as parameters, and so on. Accordingly, a decorator is also a function, and then

@decorator("params")
def myfunc(func_params):
    pass

this is the same as
def myfunc(func_params):
    pass
wrapper = decorator("params")
myfunc = wrapper(myfunc)

Nobody prevents the decorator () and wrapper () in the example from saving the address of the wrapped function into some data structure, which is then used by the bot to dispatch incoming events. Example without class:
registered_funcs = []

def decorator(param):
  #вложенная функция - фактический декоратор
  def wrapper(func):
    global registered_funcs
    #запоминаем декорируемую функцию
    registered_funcs.append( (param, func) )
    return func #не забываем её вернуть
  #возвращаем wrapper, чтобы им можно было продекорировать целевую функцию
  return wrapper

#пример использования декоратора
@decorator("foo")
def myfunc(x):
  print("Hello from myfunc(), ", x)

print(registered_funcs)
#>>> [ ("foo", <function myfunc at 0xdeadf00d>) ]
#и мы можем этим списком пользоваться, например:
for arg, func in registered_funcs:
  func(arg)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question