I have a lot of functions within functions and a lot of variables because I'm making modular 2D drawings. For that purpose I want to be able to pass a kwargs dict down into several layers of functions. As an example:
mydict = {'a':1,'b':2,'c':3}
def bar(b, c, **kwargs):
print("bar b=" + str(b))
print("bar c=" + str(c))
print("bar kwargs: ", kwargs)
def foo(a, b, **kwargs):
print("foo a=" + str(a))
print("foo b=" + str(b))
print("foo kwargs: ", kwargs)
bar(b, **kwargs)
foo(**mydict)
This returns:
foo a=1
foo b=2
foo kwargs: {'c': 3}
bar b=2
bar c=3
bar kwargs: {}
This works nicely because it catches all the kwargs I don't need. However, I need to explicitly pass kwargs that I unpacked in foo
to bar
. I would like to pass the whole mydict
down into bar
as I did in foo
while keeping it readable.
The only way I can think of doing that right now is by passing mydict
twice, where I only unpack it once and catch any unused kwargs in **_
, which doesn't seem nice.
mydict = {'a':1,'b':2,'c':3}
def bar(mydict, b, c, **_):
print("bar b=" + str(b))
print("bar c=" + str(c))
print("bar \'kwargs\': ", mydict)
def foo(mydict, a, b, **_):
print("foo a=" + str(a))
print("foo b=" + str(b))
print("foo \'kwargs\': ", mydict)
bar(mydict, **mydict)
foo(mydict, **mydict)
Which returns
foo a=1
foo b=2
foo 'kwargs': {'a': 1, 'b': 2, 'c': 3}
bar b=2
bar c=3
bar 'kwargs': {'a': 1, 'b': 2, 'c': 3}
Are there better ways to do this?
Let the functions take only **kwargs:
mydict = {'a':1,'b':2,'c':3}
def bar(**kwargs):
print("bar b=" + str(kwargs['b']))
print("bar c=" + str(kwargs['c']))
print("bar kwargs: ", kwargs)
def foo(**kwargs):
print("foo a=" + str(kwargs['a']))
print("foo b=" + str(kwargs['b']))
print("foo kwargs: ", kwargs)
bar(**kwargs)
foo(**mydict)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With