Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing default arguments to a decorator in python

I am trying to find a way to pass my function's default arguments to the decorator. I have to say I am fairly new to the decorator business, so maybe I just don't understand it properly, but I have not found any answers yet.

So here's my modified example from the Python functools.wraps manual page.

from functools import wraps
def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
            print('Calling decorated function')
            print('args:', args)
            print('kwargs:', kwds)
            return f(*args, **kwds)
    return wrapper

@my_decorator
def example(i, j=0):
    """Docstring"""
    print('Called example function')

example(i=1)

I want the j=0 to be passed, too. So the output should be:

Calling decorated function
args: ()
kwargs: {'i': 1, 'j': 0}
Called example function

But instead I get

Calling decorated function
args: ()
kwargs: {'i': 1}
Called example function
like image 940
Mike Volk Avatar asked Jul 30 '15 15:07

Mike Volk


3 Answers

Getting the exact list of args and kwargs is a little tricky, since you can pass positional args as a kwarg, or vice versa. Newer versions of python also add positional-only or keyword only arguments.

However, inspect.signature has a mechanism which can apply defaults: calling .bind(*args, **kwargs) followed by .apply_defaults(). This can give you a dictionary of effectively what all the arguments are to the function. In the example in OP, this becomes:

from functools import wraps
import inspect
def my_decorator(f):
    sig = inspect.signature(f)
    @wraps(f)
    def wrapper(*args, **kwds):
        bound = sig.bind(*args, **kwds)
        bound.apply_defaults()
        print('Calling decorated function')
        print('called with:', bound.arguments)
        return f(*args, **kwds)
    return wrapper

@my_decorator
def example(i, j=0):
    """Docstring"""
    print('Called example function')

example(i=1)

This outputs the following on Python 3.9:

Calling decorated function
called with: OrderedDict([('i', 1), ('j', 0)])
Called example function
like image 158
RecursivelyIronic Avatar answered Oct 20 '22 12:10

RecursivelyIronic


Default arguments are part of the function's signature. They do not exist in the decorator call.

To access them in the wrapper you need to get them out of the function, as shown in this question.

import inspect
from functools import wraps

def get_default_args(func):
    signature = inspect.signature(func)
    return {
        k: v.default
        for k, v in signature.parameters.items()
        if v.default is not inspect.Parameter.empty
    }

def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwds):
            print('Calling decorated function')
            print('args:', args)
            kwargs = get_default_args(f)
            kwargs.update(kwds)
            print('kwargs:', kwargs)
            return f(*args, **kwds)
    return wrapper

@my_decorator
def example(i, j=0):
    """Docstring"""
    print('Called example function')

example(i=1)

Output:

Calling decorated function
args: ()
kwargs: {'i': 1, 'j': 0}
Called example function
like image 35
Danyla Hulchuk Avatar answered Oct 20 '22 13:10

Danyla Hulchuk


You can get default argument values by using __defaults__ special attribute.

def my_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
    print('def args values', f.__defaults__)
    return f(*args, **kwds)
return wrapper

Reference: look for __defaults__ in https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy

A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value

like image 4
Shaikhul Avatar answered Oct 20 '22 13:10

Shaikhul