简体   繁体   中英

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}

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

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

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM