Home > Blockchain >  Is it possible to pass arguments to a decorator while calling a function in Python?
Is it possible to pass arguments to a decorator while calling a function in Python?

Time:05-25

Does anyone know if it's possible to pass arguments to a decorator while calling a function in Python ?

Until now, I only saw that at function definition :

@decorator("This is a decorator", 66)
def func(a: int, b: int) -> None:
    pass

But I was wondering if it was possible to do it while calling a function.

For those who are wondering why I want to do this, it's because I'm proceeding someone else's work who used decorators a lot in his code. But until now he only had to pass arguments at function definition because the function was only called once. The decorators are used to print information logs about the context the function is used but in my case, since the function can be called at different places, the context can be different in function of where the function is called.

CodePudding user response:

the short answer is no but you can modify the code of the decorator function; for example:

def decorator(func):
    def inner(*args,**kwargs):
        return func(*args,**kwargs)
    return inner

this is a standard decorator function, let's change it a little.

you could do something like this:

def decorator(func,defaultdescription,defaultnum):
    def inner(description=defaultdescription,num=defaultnum,*args,**kwargs):
        print("function",func.__code__.co_name,"with description",description,"with number",num)
        return func(*args,**kwargs)

    return inner

so you can change the description of the function

CodePudding user response:

Basically a decorator is a function inside another which calls your function after it's completion. if you are planning to use your own decorator, you must have a inner function which does it's desired task and calls the function which used the decorator function. you can use *args and **kwargs

below code is a basic implementation of the python decorator

# Python code to illustrate
# Decorators basic in Python

def decorator_fun(func):


def inner(*args, **kwargs):
    """
    do your actual task here
    """
    for argv in args:
        print(argv)

    for key in kwargs:
        print(key)
    #returning to  function which used the decorator at last
    func()
    
return inner

@decorator_fun
def func_to():
    print("Inside actual function")

func_to("hello",{"test": "value 1"})
  • Related