Answer the question
In order to leave comments, you need to log in
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
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
def myfunc(func_params):
pass
wrapper = decorator("params")
myfunc = wrapper(myfunc)
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 questionAsk a Question
731 491 924 answers to any question