TAGS :Viewed: 3 - Published at: a few seconds ago

[ How to pass kwargs to another kwargs in python? ]

def a(**akwargs):
    def b(bkwargs=akwargs):
        # how to not only use akwargs defaultly,but also define bkwargs by
        # myself?
        print bkwargs
    return b

If I wanna make the following function realized. how could I do with the code above?

>>>a(u='test')()
{'u': test}

>>>a(u='test')(u='test2')
{'u': test2}

Answer 1


It's a little unclear what you want, but I think this is the trick:

def a(**akwargs):
    def b(bkwargs=akwargs, **kwargs):
        # how to not only use akwargs defaultly,but also define bkwargs by
        # myself?
        if not bkwargs:
            bkwargs = kwargs
        else:
            # it depends what you want here (merge or replace?), but probably
            # something like bkwargs.update(kwargs) or kwargs.update(bkwargs)
    return b

Answer 2


Uses the kwargs from the outer function as default, and updates kwargs passed to the inner function.

from functools import partial

def outer(**kwargs):
    def inner(**kwargs):
        return(kwargs)
    return partial(inner, **kwargs)

This next one uses the kwargs from the outer function if no kwargs was assigned to the inner.

def outer(**outer_kwargs):
    def inner(**inner_kwargs):
        kwargs = inner_kwargs or outer_kwargs
        return kwargs
    return inner

Answer 3


Why not do the following?

def a(**akwargs):
    def b(**bkwargs):
        allkwargs = {}
        allkwargs.update(akwargs)
        allkwargs.update(bkwargs)
        print allkwargs
    return b

This uses the values from a but allows you to overwrite it by passing more to b. So:

>>> a(u='test')()
{'u': 'test'}
>>> a(u='test')(u='test2')
{'u': 'test2'}