Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give function defaults arguments from a dictionary in Python

Tags:

python

Let's imagine I have a dict :

d = {'a': 3, 'b':4}

I want to create a function f that does the exact same thing than this function :

def f(x, a=d['a'], b=d['b']):
  print(x, a, b)

(Not necessarily print, but do some stuff with the variable and calling directly from their name).

But I would like to create this function directly from the dict, that is to say, I would like to have something that look likes

def f(x, **d=d):
  print(x, a, b)

and that behaves like the previously defined function. The idea is that I have a large dictionary that contains defaults values for arguments of my function, and I would like not to have to do

def f(a= d['a'], b = d['b'] ...)

I don't know if it's possible at all in python. Any insight is appreciated !

Edit : The idea is to be able to call f(5, a=3). Edit2 : The question is not about passing arguments stored in a dict to a function but to define a function whose arguments names and defaults values are stored in a dict.

like image 922
Statistic Dean Avatar asked Aug 21 '19 13:08

Statistic Dean


People also ask

Can you set a default value for dictionary Python?

It turns out that in Python there is no good way to set a default value of a dictionary.

What is default argument in function in Python?

Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.

How do you pass a dictionary item as a function argument in Python?

“ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.

What is default arguments in functions give example?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.


1 Answers

You cannot achieve this at function definition because Python determines the scope of a function statically. Although, it is possible to write a decorator to add in default keyword arguments.

from functools import wraps

def kwargs_decorator(dict_kwargs):
    def wrapper(f):
        @wraps(f)
        def inner_wrapper(*args, **kwargs):
            new_kwargs = {**dict_kwargs, **kwargs}
            return f(*args, **new_kwargs)
        return inner_wrapper
    return wrapper

Usage

@kwargs_decorator({'bar': 1})
def foo(**kwargs):
    print(kwargs['bar'])

foo() # prints 1

Or alternatively if you know the variable names but not their default values...

@kwargs_decorator({'bar': 1})
def foo(bar):
    print(bar)

foo() # prints 1

Caveat

The above can be used, by example, to dynamically generate multiple functions with different default arguments. Although, if the parameters you want to pass are the same for every function, it would be simpler and more idiomatic to simply pass in a dict of parameters.

like image 157
Olivier Melançon Avatar answered Sep 21 '22 14:09

Olivier Melançon