Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dict as kwargs whit more variables than used

I have a dictionary with several keys and their respective values.

I want the keys to work as variables and their values as the value of each variable to use them in a function.

I understand that this allows me to have a function with any number of arguments:

def myFunc(**kwargs):
    ...

And that this allows me to use the keys in the dictionairy as arguments:

myDict={
   "foo1":"bar1",
   "foo2":"bar2",
   "foo3":"bar3"}

def myFunc(foo1, foo2):
   ...

myFunc(**myDict)

My problem is I have 3 functions that take equal arguments but they also have arguments of their own.

How can I use my dictionary as an argument for all my 3 functions provided that that dictionary has some keys that won't be used in each function.

Something like this:

myDict={
   "foo1":"bar1",
   "foo2":"bar2",
   "foo3":"bar3",
   "foo4":"bar4",
   "foo5":"bar5"}

def fun1(**kwargs):
    #takes foo1, foo2 and foo5 as args
def fun2(**kwargs):
    #takes foo1, foo2 and foo4 as args
def fun3(**kwargs):
    #takes foo1, foo2 and foo3 as args

fun1(**myDict)
fun2(**myDict)
fun3(**myDict)

How can it be done?

like image 790
BBG Avatar asked Dec 29 '25 19:12

BBG


2 Answers

I have two ways to solve this issue. First, as what you have done:

def fun1(**kwargs):
    #takes foo1, foo2 and foo5 as args
    foo1 = kwargs.get("foo1")
    foo2 = kwargs.get("foo2")
    foo5 = kwargs.get("foo5")
    # do something with foo1, foo2, foo5

You define a function with kwargs and pick up only what you need inside the function and ignore all else.

The other way is to define exactly what you need in the function signature plus a dummy kwargs:

def fun1(foo1=None, foo2=None, foo5=None, **kwargs):
    #takes foo1, foo2 and foo5 as args
    # do something with foo1, foo2, foo5

In both way, you can call the function with fun1(**myDict). Only the latter will trigger warning from a static analyser that you have unused variable kwargs, which is intentional.

like image 129
adrtam Avatar answered Dec 31 '25 09:12

adrtam


How can it be done?

This is bad API. Don't do it. Functions should be explicit about the inputs, unless there is a really good reason to accept **kwargs (e.g. you have to pass them on to somewhere else, and you don't know in advance what are the possible keywords here).

How can I use my dictionary as an argument for all my 3 functions provided that that dictionary has some keys that won't be used in each function.

Instead of having a dictionary that is the union of all arguments (foo1-foo5), use a dictionary that has the intersection of all arguments (foo1, foo2). Pass in the other arguments separately:

fun1(foo5=x, **common)
fun3(foo3=y, **common)
like image 36
wim Avatar answered Dec 31 '25 08:12

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!